duanmangxie7131 2013-10-24 14:21
浏览 44

在jquery中使用ajax回调[复制]

Im really breaking by head on this one. Ive read a lot about callbacks and know ajax is asynchronous but I cant for the life of me find how to get a value back that I can use later on in a if statement.

$.ajax({
    url: 'http://'+document.domain+'/klanten/updateaddress.php',
    type: 'post',
    data: poststring,
    success: function(result) { 
    console.log("result = "+result);    
    callbacks.add(result);

    }
});

//this doesnt work because result is generated asynchonous. 
if(result == success){
//do something
}

the console.log perfectly shows success or an error I generated in updateaddress.php and I really need to use the if statement to execute some code after it has gotten success or not. Can anyone explain to me how the callback system works in this case?

Thanks!

</div>
  • 写回答

1条回答 默认 最新

  • douji9816 2013-10-24 14:23
    关注

    Since this is async it could take a some time for this to finish. You need to pass it in a callback that will run later:

    $.ajax({
        url: 'http://'+document.domain+'/klanten/updateaddress.php',
        type: 'post',
        data: poststring,
        success: function(result) { 
            console.log("result = "+result);    
            callbacks.add(result);
            if(result == success){
                //do something
            }
    
        }
    });
    

    To explain, we don't know when that if statement will happen, but it def won't happen right away, therefore we tell javascript, run the following when you are ready.

    Google javascript callbacks for more info

    http://recurial.com/programming/understanding-callback-functions-in-javascript/

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line