jQuery:ajax调用成功后返回数据 [英] jQuery: Return data after ajax call success

查看:42
本文介绍了jQuery:ajax调用成功后返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西,它是对脚本的简单调用,它返回一个值,一个字符串..

I have something like this, where it is a simple call to a script that gives me back a value, a string..

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

但是如果我这样称呼它

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

那么我怎样才能返回值呢?下面的代码似乎也不起作用...

so how can I return the value? the below code does not seem to work either...

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

      }
   });
   return data; 
}

推荐答案

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

The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.

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

You can pass in a callback function that handles the result:

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.

这篇关于jQuery:ajax调用成功后返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆