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

Pie*_*ter 70 html php ajax jquery

我一直收到错误警报.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>
Run Code Online (Sandbox Code Playgroud)

服务器端:

<?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);
?>
Run Code Online (Sandbox Code Playgroud)

Muh*_*rar 120

如果您使用的是JSON dataType,则需要提供正确的内容类型.在回显json之前,请输入正确的标题.

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

其他修复,您应该检查查询是否成功.

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}
Run Code Online (Sandbox Code Playgroud)

在客户端:

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

希望能帮助到你.

  • 哦,您应该区分*服务器端错误*和*传输错误*。我将检查放在AJAX的“成功”部分,以检查服务器发送的值(因此这不是传输错误)。 (2认同)

Ale*_*lex 31

您知道,您可以使用它进行调试.它对我帮助很大,而且仍然如此

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*c B 22

有些人建议使用HTTP状态代码,但我宁愿鄙视这种做法.例如,如果您正在使用搜索引擎并且提供的关键字没有结果,则建议返回404错误.

但是,我认为这是错误的.HTTP状态代码适用于实际的浏览器< - >服务器连接.关于连接的一切都很完美.浏览器发出请求,服务器调用您的处理程序脚本.该脚本返回'no rows'.没有任何内容表示"找不到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);
Run Code Online (Sandbox Code Playgroud)

然后在您的客户端代码中

if (!data.error) {
   ... got data, do something with it ...
} else {
   ... invoke error handler ...
}
Run Code Online (Sandbox Code Playgroud)


phi*_*ppe 7

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

  • 一个调用Javascript,使用JQuery AJAX将数据作为POST发送(可以作为GET)
  • 一个返回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);
     }
});
Run Code Online (Sandbox Code Playgroud)

您的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));
    }
?>
Run Code Online (Sandbox Code Playgroud)