如何对php页面进行ajax调用成功或错误?

时间:2013-06-14 00:47:22

标签: php jquery html ajax

我想用jquery发送ajax请求到php页面。但我想定义我的成功和错误功能。我可以做到这一点,但在请求php页面中,我如何让它成功或错误,就像我需要调用一些特殊功能或其他东西,这导致我定义的成功或错误函数执行?

编辑:

我尝试了这个,但即使我将http_response_code代码切换为403,它也能让我获得成功。

    $.ajax({
      url: "sqlhandler.php?memberID=<?php $memberID ?>",
      success: function(){
        alert("success");
      },
      error: function() {
        alert("error");
      }
    });

sqlhandler.php

<?php
    http_response_code(200);
?>

4 个答案:

答案 0 :(得分:5)

投掷200获得良好反应,投掷4xx获得不良反应:http://php.net/manual/en/function.http-response-code.php

如果用户试图看到他们不应该看到的内容,请使用http_response_code(403);(禁止)。

如果他们尝试查看不存在的内容,请使用404。

如果您不喜欢它们,请使用403作为全能。

有关在jQuery中捕获这些错误代码的更多信息:http://www.unseenrevolution.com/jquery-ajax-error-handling-function以下是从该页面复制的示例:

$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});

答案 1 :(得分:1)

HTTP状态代码是指示请求是成功还是失败的方式。

PHP的http_response_code设置状态代码。

在您传递给$.ajax的对象中,您可以将error成员定义为所有3xx4xx5xx的全部内容状态代码,或者您可以定义statusCode对象以使用不同的函数处理每个状态代码。

答案 2 :(得分:1)

当您进行任何HTTP(AJAX或其他)调用时,都会有响应代码。有很多,例如错误代码200表示OK,4xx调用意味着错误(例如,404表示“找不到页面”错误)。

你应该对它们进行一些研究。

答案 3 :(得分:1)

我通常使用以下代码:

.done(function(msg){
if(msg==1)
   alert("Success");
else
   alert("Failure");
})

根据您从PHP脚本传递的内容,您可以更改代码。