derek5. 2011-03-15 19:08 采纳率: 100%
浏览 484
已采纳

Jquery: 在 ajax 调用成功后返回数据[重复]

This question already has an answer here:

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; 
      }
   });
}

but if I call something like this

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; 
}
</div>

转载于:https://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success

  • 写回答

5条回答 默认 最新

  • 狐狸.fox 2011-03-15 19:13
    关注

    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); 
        }
      });
    }
    

    Call it like this:

    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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器