Unable to get return from jQuery AJAX Success function
Hey guys, I'm building an application which requires access to the server time before sending AJAX requests off, the only way to do this is to be able to have a function that requests the time from the server using AJAX, so in my function I have the following code:
$.ajax({
type:"GET",
url:"app/time.php",
success: function(html){ return html; } });
In itself the code is fine, but as it is, I am unable to gain access to the returned HTML, meaning the data is useless to me. I've tried sending the data to another function, and even back on the same function, and it simply adds complexity that I don't think is开发者_StackOverflow中文版 needed. I've also tried setting the value of the HTML to another variable and then using, but this doesn't work outside of the function.
So I'm asking if there is an easy way to have access to the returned "html" variable from the AJAX request so I can set variables on the page equal to the function?
Do it like this :
function getTime() {
$.ajax({
type:"GET",
url:"app/time.php",
success: function(html){ setTime(html); } });
}
function setTime(time){
//do what ever you want with time
}
when ever you call time getTime()
an ajax called will be made and the function setTime()
will be called, and will get time through its argument.
or you can do it like this
function getTime() {
$.ajax({
type:"GET",
url:"app/time.php",
success: function(time){ // do what ever with time ; } });
}
I think this way its easier but if you have a long function then the previous one is cleaner I think.
You cannot return a value from there. It's an asynchronous function which is fired when the XHR's request has completed successfully. You need to invoke another callback here:
function getTime(cb) {
.ajax({
type:"GET",
url:"app/time.php",
success: function(html){ cb(html); }
});
}
getTime(function(html) {
// do something with html
});
精彩评论