使用ajax

时间:2018-08-21 11:53:00

标签: javascript jquery ajax global-variables

我有一个转到PHP脚本的函数,该脚本返回服务器操作系统。

该脚本实际上非常简单:

<?php
    echo (strpos(PHP_OS, 'Linux') > -1 ? 'Lin' : 'Win');

我的目标是能够区分操作系统,以便我可以在.js文件中声明全局路径变量以供将来使用。

这是我到目前为止所做的:

function serverOS()
{
    var os;

    $.ajax({
        url: '../scripts/ajax/detect-os.php',
        type: 'get',
        success: function(res)
        {
            os = res;
            return os;
        },
        error: function(res) {alert('Major Error!'); console.log(res)}
    });

    return os;
}

console.log(serverOS());

结尾的console.log输出undefined-但是如果我在成功回调函数中console.log os,那么它输出的是我所期望的。

据此:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

我应该可以使用上面的脚本做我想做的事,但它似乎不起作用。如何在JavaScript / jQuery中使用Ajax设置和获取全局变量?

2 个答案:

答案 0 :(得分:2)

AJAX操作是异步的。它们不会阻止您的JavaScript其余部分执行。

函数中的最终return语句尝试立即返回os(在AJAX操作完成之前。删除该return语句,并在成功处理程序中处理所有逻辑将值返回给调用者。

function serverOS() {
  // The AJAX method will invoke the logging function no matter what.
  // But, it won't happen until the AJAX call is complete.
  $.ajax({
    url: '../scripts/ajax/detect-os.php',
    type: 'get',
    success: function(res) {
      returnValue(res);
    },
    error: function(res) {
      alert('Major Error!');
      returnValue(res);
    }
  });
}
 
function returnValue(val){
  console.log(val);
}

serverOS();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

斯科特的答案肯定有效-但似乎确实有我偶然发现的另一种选择。有一个名为async的AJAX属性。在我的函数中将此设置为false意味着它成为一个同步ajax调用。将我的功能更改为此:

var os;

function serverOS()
{
    $.ajax({
        url: '../scripts/ajax/detect-os.php',
        type: 'get',
        async: false,
        success: function(res)
        {
            returnValue(res)
        },
        error: function(res)
        {
            alert('Major Error!');
            returnValue(res)
        }
    });
}

function returnValue(val)
{
    os = val;
    return os;
}

serverOS();

console.log(os); //this print Lin on my Linux machine.

ref:https://api.jquery.com/jQuery.ajax/