简体   繁体   English

无法似乎正确设置全局变量

[英]Cant seem to set global vars correctly

I am trying to store a token into a global var. 我正在尝试将令牌存储到全局变量中。 When the alert is run it says null, but if I put 2 alerts one after the other the 1st shows null but the second shows the token. 运行警报时,它表示为空,但是如果我将2个警报一个接一个放置,则第一个显示为空,但是第二个显示令牌。

Its like the token is not being set because the 1st alert is run before the ajax request has finished. 就像没有设置令牌一样,因为第一个警报是在ajax请求完成之前运行的。

Does anyone have any ideas on what I am doing wrong? 有人对我在做什么错有任何想法吗?

var csrf_token = null;

$(document).ready(function(){
    get_csrf_token();
    alert('token 1 '+csrf_token);
    alert('token 2 '+csrf_token);
});

function get_csrf_token()
{
    $.ajax({
        type: "GET",
        url: "http://buscore/index.php/includes/csrf_token/",
        dataType: "json",
        success: function(resp, status) {
            if (resp.status != 'success')
            {
                alert('Error - Update CSRF Token\n\n' + resp.status);
                return;
            }

            csrf_token = resp.csrf_token;
        }
    });
}

Thanks 谢谢

UPDATED 更新

Ok thanks for your help everyone but still dont see how this would work. 好的,谢谢大家的帮助,但仍然看不到它如何工作。 I use get_csrf_token() like jqgrid to send the token with the request like below. 我使用jqgrid之类的get_csrf_token()来发送令牌,如下所示。 So how do I pass the token to and have it working? 那么我如何将令牌传递给它并使它工作呢?

beforeRequest: function (){
        get_csrf_token()
        //alert(csrf_token);
        $("#customer_grid").setPostDataItem('<?php echo $csrf_token_name; ?>', csrf_token);
    }

The success callback function runs when the HTTP response arrives. HTTP响应到达时,将运行成功回调函数。

In your test, the response is arriving between the time that the first alert is displayed and the time you click the button to let the script continue. 在您的测试中,响应在显示第一个警报的时间与您单击按钮以使脚本继续的时间之间到达。

Do whatever you need to do with the data in the callback, not as the statement after the one where you initiate the Ajax request. 对回调中的数据做任何您需要做的事情,而不要像在启动Ajax请求的那条语句之后那样做。

Example as requested by comment: 注释要求的示例:

$(document).ready(function(){
    get_csrf_token();
});

function get_csrf_token()
{
    $.ajax({
        type: "GET",
        url: "http://buscore/index.php/includes/csrf_token/",
        dataType: "json",
        success: function(resp, status) {
            if (resp.status != 'success')
            {
                alert('Error - Update CSRF Token\n\n' + resp.status);
                return;
            }

            alert('token 1 '+csrf_token);
            alert('token 2 '+csrf_token);
        }
    });
}

The AJAX request is async. AJAX请求是异步的。 That means the script doesn't wait for it to finish. 这意味着脚本不会等待它完成。 When the first alert fires the token is not set. 当第一个警报触发时,未设置令牌。 But until you hit OK it has time to load and the token will be set. 但是直到您单击确定,它才有时间加载并且令牌将被设置。

Here's the order of the operations: 操作顺序如下:

  1. call get_csrf_token 呼叫get_csrf_token
  2. make token request 提出令牌请求
  3. show alert 1 显示警报1
  4. finish request and set csrf_token 完成请求并设置csrf_token
  5. client hits OK on the first alert 客户在第一个警报上点击“确定”
  6. show alert 2 (the token variable was set at 4.) 显示警报2(令牌变量设置为4。)

The A in AJAX stands for 'asynchronous'. AJAX中的A代表“异步”。 While you are busy clicking on the first alert, the AJAX request is going through and the value is filled. 当您忙于单击第一个警报时,AJAX请求正在处理中,并且该值已填充。 You will need to place all code that needs the variable csrf_token into your callback function. 您将需要将需要变量csrf_token的所有代码放入回调函数中。 Alternatively, you can look into using jQuery 1.5 or above (if you aren't already). 另外,您可以考虑使用jQuery 1.5或更高版本(如果尚未使用)。 It has so-called Deferred Objects 它有所谓的延期对象

This API allows you to work with return values that may not be immediately present (such as the return result from an asynchronous Ajax request). 该API允许您使用可能不会立即出现的返回值(例如异步Ajax请求的返回结果)。

You can also set the async value on your post request to false , like this: 您还可以将发布请求上的async值设置为false ,如下所示:

$.ajax({
    type: "GET",
    async: false,
    url: "http://buscore/index.php/includes/csrf_token/",
    dataType: "json",
    success: function(resp, status) {
        if (resp.status != 'success')
        {
            alert('Error - Update CSRF Token\n\n' + resp.status);
            return;
        }

        csrf_token = resp.csrf_token;
    }
});

This will make the browser wait for the response before proceeding with the rest of your code. 这将使浏览器在继续其余代码之前等待响应。 I wouldn't necessarily recommend it, but it should work. 我不一定会推荐它,但是应该可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM