返回从jQuery的AJAX调用的响应jQuery、AJAX

2023-09-10 19:13:06 作者:白桃汽水贩卖机

我写了一个函数,该函数来检查用户名是否已采取或不。现在,当我打电话从另一个函数的函数,并提醒它的返回值:

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')); 

它说:未定义。我搜索高和低,但无法找到我在做什么错。我想这应该只是返回PHP的回声check.php,但事实并非如此。下面是我写的函数:

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:

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?

推荐答案

AJAX调用是异步的,这意味着他们只操作完成后,返回的数据。即该方法 checkusernameavailable 不会返回任何信息(除非你告诉它该方法本身)。你需要做到以下几点:

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:

// 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);     
  },

该方法触发AJAX异步方法职位check.php。当接收到响应,你再处理与 $的成功回调关联函数的响应。AJAX 。您可以直接指定一个函数,成功的回调,以及:

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:

// Change success to point to a function name
success: foo

// Create a function to handle the response
function foo(response)
{
   // Do something with response
}

编辑:

根据业务方案的意见,你需要改变你的AJAX调用是同步的,而不是异步(我从来没有做过一个同步调用这样的自己,所以这是未经测试):

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):

var ajaxResponse;

$.ajax({
    async: false, 
    success : function (response)
              {
                  ajaxResponse = response;
              },
    // other properties
});

return ajaxResponse;

完整的API上市这里。

 
精彩推荐
图片推荐