jQuery ajax output as return of a function
I created a small php script that returns a mysql result depending on given post/get parameters. With this file I can now use the jquery.post or .get command to retrieve something from my database.
The script always returns 1 value. So I tried to ma开发者_如何学编程ke a javascript function that returns the retrieved value from the database.
This is what I WANT it to do but I does not work like it should:
function mysql(args) {
$.post("scripts/ajax_mysql.php",args,function(data) {
return data;
});
}
var value=mysql({ table:"user", where:"nickname='test'", get:"email" });
It seems the data is retrieved when the function has already been passed. Is there a workaround for this?
Putting aside the issue of letting the user basically create any sort of SQL command and send it to your server -- a horrible idea with terrible security implications, the problem with your script is a failure to understand the nature of AJAX.
The AJAX call is asynchronous so your method is returning before the AJAX call completes. You have two ways to deal with this. Pass in a callback to your function and have the callback execute when the AJAX post completes. This keeps the asynchronous nature of the request. Alternatively, you can use the full $.ajax() syntax to do the post and set the async
parameter to true. You can then store the results of the AJAX request in a variable scoped to the outer block in your function and return it at the end of the function. Setting async
to true basically does what using the callback does, except jQuery handles it under the hood.
function mysql(data, callback) {
$.post( "scripts/ajax_mysql.php",args,function(data) {
if (callback) {
callback(data);
}
});
}
mysql({ table:"user", where:"nickname='test'", get:"email" }, function(user) {
$('#email').val(user.email);
...
});
or
function mysql(data, callback) {
var value;
$.ajax({
url: "scripts/ajax_mysql.php",
type: 'post',
async: false,
data: args,
success: function(data) {
value = data;
}
});
return value;
}
with your existing call semantics.
Ajax is asynchronous. Calling the function fires a request, and then the program continues.
When the request comes back, and event fires, and an attached event handler deals with the data.
You can use XHR to make a synchronous, but it isn't recommended.
Design your program to deal with the retrieved data in the callback, not as a returned variable.
The problem is that the return data
statement doesn't cause a "return" in the mysql function.
What I would do is to from the mysql function return the XMLHTTPRequest object the $.post
call returns, and then add an listener for a successful ajax call.
精彩评论