weixin_33701564 2011-12-16 09:22 采纳率: 0%
浏览 264

$ .post()调用的返回值

I have a jquery $.post function lik so:

$.post('/test',json_data, function(data) {
                                result=data
});

this function is actually being used in an validation...So it the return value(data) contains true or false. But this value is not being stored in the variable 'result'. I understand that this is because post makes an asynchronous call and hence it does'nt wait for the response. What I want to ask is, is there some workaround for this? or can this call be made synchronous somehow??

  • 写回答

2条回答 默认 最新

  • weixin_33691598 2011-12-16 09:25
    关注

    This is considered a bad practice but there is an async parameter in $.ajax() that you can set to false and wait synchronously for a result:

    var result;
    $.ajax({
      type: 'POST',
      url: '/test',
      data: json_data,
      async: false,
      success: function(data) {
        result=data;
      },
      dataType: 'application/json'
    });
    //result available here
    

    A more idiomatic, although slightly less convenient in this case, would be to take advantage of callbacks:

    function validate(okCallback, errorCallback) {
        $.post('/test',json_data, function(data) {
            if(data) {
                okCallback();
            } else {
              errorCallback();
            }
        });
    }
    
    validate(
        function() {
            //proceed
        },
        function() {
            //display validation error
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog