Ok so I have this function:
function getAreas(){
$.post("/custom_html/weathermap.php",'',
function(data){
return data
}, "json");
}
which works fine. now what I am trying to do i开发者_C百科s 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?
Thanx in advance for any help.
It's an asynchronous call, so you can't return from it like that.
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");
}
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.
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
You can archive that by setting async to 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;
}
The function is called asynchronously - that means that the call back part is executed at some point in the future while your main getAreas() function returns immediately. In this case, it returns nothing because you don't have a return statement in your main function.
To get this working, you need to separate your code into what needs to happen before you call getAreas() and what happens afterwards.
Then you might end up with something like:
function getAreas(){ $.post("/custom_html/weathermap.php",'', onGetAreasComplete, "json");
}
function onGetAreasComplete(data)
{
// do whatever you need to do with data
}
// do whatever you need to do before getAreas()
getAreas();
Hope that makes sense.
Try this
function getAreas(){
var ret;
$.post("/custom_html/weathermap.php",'', function(data){
ret = data;
}, "json");
return ret;
}
精彩评论