jquery返回post数据 [英] Jquery return post data

查看:27
本文介绍了jquery返回post数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有这个功能:

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

                return data

            }, "json");


}

效果很好.现在我要做的是将数据传回一个变量,换句话说:

which works fine. now what I am trying to do is to pass the data back to a variable, in other words:

var data=getAreas()

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

but it doesnt return anything. is there a way to get this working?

感谢任何帮助.

推荐答案

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

It's an asynchronous call, so you can't return from it like that.

您必须将与 data 相关的代码移动到回调函数 (function(data){}).

You'll have to move the code that does something with data into the callback function (function(data){}).

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

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

            }, "json");
}

您需要一段时间才能进入异步思维方式,但您会解决的.基本上,发送请求的代码在发送请求后就完成了.该执行线程将完成,您的浏览器将坐在那里,不做任何事情.那么 $.post 调用将从 weathermap.php 中获取数据,并且您的回调函数将被调用.这开始了一个全新的执行线程.试着把它们想象成两个完全独立的执行,一个 pre-ajax 调用和一个 post-ajax 调用.

It takes a while to get your head into the asynchronous way of thinking, but you'll work it out. Basically, the bit of code that sends the request is done once the request is sent. That thread of execution will finish, and your browser will just sit there, not doing anything. then the $.post call will get the data back from weathermap.php, and your callback function will be called. That starts a whole new thread of execution. Try to think of them as two completely separate executions, one pre-ajax call and one post-ajax call.

这里有一些 ascii 优点:

Here's some ascii goodness:

       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

这篇关于jquery返回post数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆