小编典典

jQuery:在ajax调用成功之后返回数据

javascript

我有这样的事情,它是对脚本的简单调用,该脚本给了我一个值,一个字符串。

function testAjax() {
    $.ajax({
      url: "getvalue.php",  
      success: function(data) {
         return data; 
      }
   });
}

但是如果我这样称呼

var output = testAjax(svar);  // output will be undefined...

那么我该如何返回值?下面的代码似乎也不起作用…

function testAjax() {
    $.ajax({
      url: "getvalue.php",  
      success: function(data) {

      }
   });
   return data; 
}

阅读 290

收藏
2020-04-23

共1个答案

小编典典

从该函数返回数据的唯一方法是进行同步调用而不是异步调用,但这将使浏览器在等待响应时冻结。

您可以传入一个处理结果的回调函数:

function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    success:function(data) {
      handleData(data); 
    }
  });
}

这样称呼它:

testAjax(function(output){
  // here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.
2020-04-23