美元.ajax从PHP文件中获取返回值


$.ajax get return value from a PHP file

这里有jQuery ajax调用。php文件有时会执行下面的代码

echo "hello"

在这里:

    $.ajax({
        type: "POST",
        url: myurl.php
        data: data_string,
        timeout: 6000,
        success: function () {
        }
    });

我想知道:是否有可能使ajax返回错误,而不是成功时,像以前的echo在PHP文件中执行?我的意思是,检查这个$。

如果php文件被执行,

解释更好:当请求无法完成时我得到错误,当它可以完成时我得到成功。但我想从这个PHP文件中得到一个返回值。如果它返回1,我想做点什么。如果它返回2,我想做别的事情。

我建议在PHP文件中使用json_encode()。例如:

echo json_encode(array('success' => 'do_foo'));
exit();

然后你可以在成功回调中添加一个条件:

$.ajax({
  type: "POST",
  url: myurl.php
  data: data_string,
  dataType: "JSON", //tell jQuery to expect JSON encoded response
  timeout: 6000,
  success: function (response) {
    if (response.success === 'hello'){
      console.log(response);
    } else {
      console.log('else');
    }
  }
});

根据您的问题使php返回1或返回2。您可以使它在失败时返回1,在成功时返回0(即null)。然后,您可以为ajax返回执行此操作。

$.ajax({
                type: "POST",
                url: "YOUR URL",
                data: dataString,
                success: function(server_response)
                    {
                        if(server_response == 1)
                        {
                            alert("You have made a mistake");
                            return true;
                        }
                        HERE YOU WILL PUT WHAT HAPPENS ON SUCCESS
                        }
                    });
$.ajax({
    type: "POST",
    url: myurl.php
    data: data_string,
    timeout: 6000,
    success: function (msg) {
       if (msg != "Hi")
       {
          //TODO
       } else
       {
          //TODO
       }
    }
});

你可以使用错误回调:

$.ajax({
    type: "POST",
    url: myurl.php
    data: data_string,
    timeout: 6000,
    success: function () {
    },
    error: function() {
        /* Code reacting to error here */
    }
});

此外,还有其他回调机会,您可以在$中查看。Ajax文档页。

如果你要从PHP中"说"有错误,这可以通过两种方式完成:

你可以在PHP中打印一个表示错误的关键字,然后在success函数中检查它:

success: function (data) {
    if (data == 'error') {
    } else {
    }
}

或者,另一种方式,你可以提供PHP正确的头导致"error"。然后,您可以像往常一样使用错误回调。