jQuery:ajax调用成功后返回数据
问题描述:
我有这样的东西,它是对脚本的简单调用,它返回一个值,一个字符串..
I have something like this, where it is a simple call to a script that gives me back a value, a string..
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
return data;
}
});
}
但是如果我这样称呼它
var output = testAjax(svar); // output will be undefined...
那么我怎样才能返回值呢?下面的代码似乎也不起作用...
so how can I return the value? the below code does not seem to work either...
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
}
});
return data;
}
答
从函数返回数据的唯一方法是进行同步调用而不是异步调用,但这会在等待时冻结浏览器为响应.
The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.
可以传入一个处理结果的回调函数:
You can pass in a callback function that handles the result:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}
这样称呼它:
testAjax(function(output){
// here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.