Javascript 从 Jquery AJAX 调用返回响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3880361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning the response from an Jquery AJAX call
提问by Joris Portfolioris
I have written a function, which has to check whether a username has been taken or not. Now when I call the function from another function, and alert it's return value:
我写了一个函数,它必须检查用户名是否被占用。现在,当我从另一个函数调用该函数时,并警告它的返回值:
alert(checkusernameavailable('justausername'));
it says 'undefined'. I've searched high and low, but can't find what I'm doing wrong. I guess it should just return the php-echo in check.php, but it doesn't. Here's the function I wrote:
它说“未定义”。我搜索了高低,但找不到我做错了什么。我想它应该只返回 check.php 中的 php-echo,但它没有。这是我写的函数:
var checkusernameavailable = function(value) { $.ajax({ url: "check.php", type: "POST", async: false, cache: false, data: "username=" + value + "", success: function(response) { alert(response); return response; }, error: function() { alert('ajax error'); } }); }
What am I doing wrong?
我究竟做错了什么?
回答by djdd87
AJAX calls are async, which means they only return data after the operation has completed. I.e. the method checkusernameavailable
never returns any information (unless you tell it to within that method itself). You need to do the following:
AJAX 调用是异步的,这意味着它们仅在操作完成后返回数据。即该方法checkusernameavailable
从不返回任何信息(除非您在该方法本身内告诉它)。您需要执行以下操作:
// Just fire and forget the method
checkusernameavailable("userName");
// Change the success function to do any display you require
success: function(response) {
alert(response);
$("#SomeDiv").html(response);
},
The method fires the AJAX async method that posts to check.php. When the response is received, you then handle that response in function associated with the success callback of $.ajax
. You can specify a function directly to that success callback as well:
该方法触发发送到 check.php 的 AJAX 异步方法。收到响应后,您可以在与成功回调关联的函数中处理该响应$.ajax
。您也可以直接为该成功回调指定一个函数:
// Change success to point to a function name
success: foo
// Create a function to handle the response
function foo(response)
{
// Do something with response
}
EDIT:
编辑:
As per the OP's comment, you need to change your AJAX call to be synchronous, instead of asynchronous (I've never done a synchronous call like this myself, so this is untested):
根据 OP 的评论,您需要将 AJAX 调用更改为同步调用,而不是异步调用(我自己从未做过这样的同步调用,因此未经测试):
var ajaxResponse;
$.ajax({
async: false,
success : function (response)
{
ajaxResponse = response;
},
// other properties
});
return ajaxResponse;
Full API listing here.
完整的 API 列表在这里。