如何使用PHP为JQuery.ajax()返回正确的成功/错误消息


How do I return a proper success/error message for JQuery .ajax() using PHP?

我一直收到错误警报。MYSQL部分没有错,查询被执行,我可以在数据库中看到电子邮件地址。

客户端:

<script type="text/javascript">
  $(function() {
    $("form#subsribe_form").submit(function() {
      var email = $("#email").val();
      $.ajax({
        url: "subscribe.php",
        type: "POST",
        data: {email: email},
        dataType: "json",
        success: function() {
          alert("Thank you for subscribing!");
        },
        error: function() {
          alert("There was an error. Try again please!");
        }
      });
      return false;
    });
  });
</script>

服务器端:

<?php 
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^'.'-'_'@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
    $query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';    
echo json_encode($response_array);
?>

如果使用JSON数据类型,则需要提供正确的内容类型。在回显json之前,请放置正确的头。

<?php    
    header('Content-type: application/json');
    echo json_encode($response_array);
?>

附加修复程序,您应该检查查询是否成功。

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

在客户端:

success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
},

希望能有所帮助。

您可以使用它进行调试。它帮了我很多,现在仍然如此

error:function(x,e) {
    if (x.status==0) {
        alert('You are offline!!'n Please Check Your Network.');
    } else if(x.status==404) {
        alert('Requested URL not found.');
    } else if(x.status==500) {
        alert('Internel Server Error.');
    } else if(e=='parsererror') {
        alert('Error.'nParsing JSON Request failed.');
    } else if(e=='timeout'){
        alert('Request Time out.');
    } else {
        alert('Unknow Error.'n'+x.responseText);
    }
}

有些人建议使用HTTP状态代码,但我不喜欢这种做法。例如,如果你正在使用搜索引擎,而提供的关键字没有结果,建议返回404错误。

然而,我认为这是错误的。HTTP状态代码适用于实际浏览器<->服务器连接。连接的一切都很顺利。浏览器发出请求,服务器调用您的处理程序脚本。脚本返回"无行"。其中没有任何内容表示"404页面未找到"-页面WAS已找到。

相反,我赞成将HTTP层与服务器端操作的状态分离。我总是返回一个封装请求状态和请求结果的json数据结构,而不是简单地在json字符串中返回一些文本。

例如,在PHP中,你会有

$results = array(
   'error' => false,
   'error_msg' => 'Everything A-OK',
   'data' => array(....results of request here ...)
);
echo json_encode($results);

然后在你的客户端代码中,你会有

if (!data.error) {
   ... got data, do something with it ...
} else {
   ... invoke error handler ...
}

为了构建AJAX Web服务,您需要两个文件:

  • 使用JQueryAJAX以POST(可以是GET)形式发送数据的调用Javascript
  • 返回JSON对象的PHP Web服务(这样可以方便地返回数组或大量数据)

因此,首先在JavaScript文件中使用JQuery语法调用Web服务:

$.ajax({
     url : 'mywebservice.php',
     type : 'POST',
     data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
     dataType : 'json',
     success: function (data) {
          alert("The file is "+data.fichierZIP);
     },
     error: function(data) {
          //console.log(data);
          var responseText=JSON.parse(data.responseText);
          alert("Error(s) while building the ZIP file:'n"+responseText.messages);
     }
});

您的PHP文件(mywebservice.PHP,如AJAX调用中所写)的末尾应该包含这样的内容,以返回正确的成功或错误状态:

<?php
    //...
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
    //$errors is a string that may contain an error message while preparing the ZIP file
    //In the end, I check if there has been an error, and if so, I return an error object
    //...
    if ($errors==''){
        //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['ZIPFILENAME'] = basename($filename); 
        print json_encode($result);
    } else {
        //if there is an error, you should return a special header, followed by another JSON object
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['messages'] = $errors;
        //feel free to add other information like $result['errorcode']
        die(json_encode($result));
    }
?>

服务器端:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

客户端:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

添加到顶部答案:以下是一些来自PHP和Jquery的示例代码:

$("#button").click(function () {
 $.ajax({
            type: "POST",
            url: "handler.php",
            data: dataString,
                success: function(data) {
                  if(data.status == "success"){
                 /* alert("Thank you for subscribing!");*/
                   $(".title").html("");
                    $(".message").html(data.message)
                    .hide().fadeIn(1000, function() {
                        $(".message").append("");
                        }).delay(1000).fadeOut("fast");
                 /*    setTimeout(function() {
                      window.location.href = "myhome.php";
                    }, 2500);*/

                  }
                  else if(data.status == "error"){
                      alert("Error on query!");
                  }


                    }

        });
        return false;
     }
 });

PHP-发送自定义消息/状态:

    $response_array['status'] = 'success'; /* match error string in jquery if/else */ 
    $response_array['message'] = 'RFQ Sent!';   /* add custom message */ 
    header('Content-type: application/json');
    echo json_encode($response_array);

我遇到了同样的问题。我的问题是我的标题类型设置不正确。

我刚刚在json echo 之前添加了这个

header('Content-type: application/json');

。。。您可能还想检查跨站点脚本问题。。。如果您的html页面来自与rest服务不同的域/端口组合,则浏览器可能会阻止该调用。

通常,用鼠标右键->在html页面上进行检查。然后在错误控制台中查找类似的错误

访问位于"…"的XMLHttpRequest:8080"来自原点"…:8383'已被阻止CORS策略:请求的上不存在"Access Control Allow Origin"标头资源