weixin_33696822 2012-10-17 13:59 采纳率: 0%
浏览 71

将数据从$ .post设置为var

The code:

 $.post('script.php',{value:value},function(data)
 {
        var Aquaman= ???;
 });

Now my question is if I want to set the data value into the Aquaman variable, how do I do it?

  • 写回答

3条回答

  • ℡Wang Yan 2012-10-17 14:04
    关注

    Welcome to the wonderful world of asynchronous logic.

    All you need to do is var Aquaman = data; -- however, that variable will ONLY exist inside that anonymous function.

    You can get around this by assign global variables in the usual manner:

     var Aquaman;
     $.post('script.php',{value:value},function(data) {
          Aquaman= data;
     });
    

    However, this global variable won't be set until after your AJAX call is completed. This may be desirable if, for instance, Aquaman is being called by other AJAX calls or user events. However, the following code won't work as you might expect:

     var Aquaman;
     $.post('script.php',{value:value},function(data) {
          Aquaman= data;
     });
     console.log(Aquaman); // displays nothing
    

    ...because console.log() is run immediately and before the $.post() is completed.

    The only way to prevent that is to make a synchronous AJAX call:

    $.ajax({url: 'script.php', data: {value:value}, async: false}, function(data) {...});
    

    ...but this nullifies most of the advantages of AJAX by forcing your script to stop and wait for the callback to complete. In almost all cases, it's better to let your AJAX remain asynchronous and deal with the data inside the callback.

    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面