Jquery返回发布数据

lol*_*lla 3 jquery post return function

好的,我有这个功能:

function getAreas(){
      $.post("/custom_html/weathermap.php",'',
            function(data){

                return data

            }, "json");


}
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.现在我要做的是将数据传递回变量,换句话说:

var data=getAreas()
Run Code Online (Sandbox Code Playgroud)

但它不会返回任何东西.有没有办法让这个工作?

Thanx提前提供任何帮助.

Ski*_*ick 13

这是一个异步调用,所以你不能这样回来.

您必须将执行某些操作的代码移动data到回调函数(function(data){})中.

function getAreas(){
      $.post("/custom_html/weathermap.php",'',
            function(data){

                //do something with data here, such as calling another function

            }, "json");
}
Run Code Online (Sandbox Code Playgroud)

让你的头脑进入异步思维方式需要一段时间,但你会解决它.基本上,一旦发送请求,就会完成发送请求的代码位.执行线程将完成,您的浏览器将只是坐在那里,没有做任何事情.然后$.post调用将从中获取数据weathermap.php,并调用您的回调函数.这开始了一个全新的执行线程.尝试将它们视为两个完全独立的执行,一个pre-ajax调用和一个post-ajax调用.

这是一些ascii善良:

       V
       |
User clicks button
(or something else happens)
       |
       |
Your JavaScript runs   
       |
       |
And eventually gets
to the ajax call     -------> SERVER ------>     Server sends data back
                                                           |
                                                           |
                                                 And your callback is run
                                                 on the data and execution
                                                 continues from here
                                                           |
                                                           |
                                                           V
Run Code Online (Sandbox Code Playgroud)


ang*_*iwi 6

您可以通过将async设置为false来存档

jQuery.loadView = function(url,data){
    var idata;
    $.ajax({
      type: 'POST',
      url: url,
      data: data,
      dataType: 'html',
      async: false,
      success: function(result){idata = result;}
    });
    return idata;
}
Run Code Online (Sandbox Code Playgroud)