Javascript 如何将变量设置为 AJAX 响应数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13523127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:16:49  来源:igfitidea点击:

How to set a variable to a AJAX response data?

javascriptjqueryajaxfunctionscope

提问by user12882

I am using jQuery and I have the following code:

我正在使用 jQuery,我有以下代码:

var result = [];

if ( some_condition ) {
  result = [...]
} else {
  $.ajax({
    url:      some_url,
    data:     some_data,
    dataType: 'json',
    success:  function(data) {
      items = data
    }
  });

  result = items
}

// Playing with the 'result' variable...

The above code generates the error "items is not defined" when some_conditionis false(I think it happens because the variable scope is not correct).

上面的代码生成错误“ items is not defined” when some_conditionis false(我认为这是因为变量作用域不正确)。

I would like to set the resultvariable to the AJAX response data but I don't know how to solve the problem.

我想将result变量设置为 AJAX 响应数据,但我不知道如何解决问题。



Note: I am trying to do that because I would like to use the resultvariable outsidethe if ... elsestatement (that is, afterthe if ... elsestatement in the above code).

注意:我尝试这样做是因为我想在语句之外使用result变量(即,上述代码中的语句之后)。if ... elseif ... else

回答by Flavio

Simply make the ajax function no async

简单地让ajax函数没有异步

var result = [];

if ( some_condition ) {
  result = [...]
} else {
    $.ajax({
    url:      some_url,
    data:     some_data,
    dataType: 'json',
    async: false, 
    success:  function(data) {
        items = data
    }
    });
   result = items
}

回答by Akhil Sekharan

Do this:

做这个:

Since you are calling it async, you should assign it in your callback function

由于您将其称为异步,因此您应该在回调函数中分配它

var result = []; 


if ( some_condition ) {
  result = [...]
} else {
  $.ajax({
    url:      some_url,
    data:     some_data,
    dataType: 'json',
    success:  function(data) {
      result = data;
      validateResult(result);
    }
  });
}

And for your better understanding.

并且为了您更好的理解。

Your result array is a global variable.

您的结果数组是一个全局变量。

  1. Initially its an array with length = 0;
  2. You call your ajax function.
  3. The length of result array is still 0.
  4. Ajax call completes and success function is executed.
  5. In success function you assign result to your response data.
  6. Now the length of result array is not zero any more .
  7. Globally the value is updated.
  8. You can use result array anywhere in your code
  1. 最初它是一个长度为 0 的数组;
  2. 你调用你的 ajax 函数。
  3. 结果数组的长度仍然为0。
  4. Ajax 调用完成并执行成功函数。
  5. 在成功功能中,您将结果分配给您的响应数据。
  6. 现在结果数组的长度不再为零。
  7. 全局更新该值。
  8. 您可以在代码中的任何位置使用结果数组