ajax如何从PHP文件返回错误消息

当我将鼠标hover在任何单词上时,总会显示黑匣子。 如果PHP代码返回文本,它将显示在黑匣子中(它应该)。 但是我希望它返回一个错误函数,如果没有返回文本,那么我可以稍后更改黑盒子的CSS,使其宽度为0px而不是400px

 var x = ($(this).text()); $.ajax({ type: 'POST', url: 'process.php', data: { text1: x }, success: function(response){ $('#tooltip').text(response); } }); 
 try { $db = new PDO('sqlite:ordbas.db'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $err) { echo "PDO fel $err"; } if (isset($_POST['text1'])) { $text1 = $_POST['text1']; $results = $db->prepare("SELECT forord FROM words WHERE sokord='$text1'"); $results->execute(); $row = $results->fetch(); echo $row[0]; } 

正如您可能已经想到的那样,我遗漏了一些非重要的代码。 我希望有人能理解并帮助我! 谢谢!

以下是您如何做到这一点:

非常简单的方法:

在你的PHP文件中:

 if ($query) { echo "success"; //anything on success } else { die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure } 

在你的jQuery AJAX SIDE:

 var x = ($(this).text()); $.ajax({ type: 'POST', url: 'process.php', data: { text1: x }, success:function(data) { alert(data); //=== Show Success Message== }, error:function(data){ alert("error occured"); //===Show Error Message==== } }); 

$.ajaxfail回调用于捕获任何失败的结果。

根据服务器脚本返回的成功/失败显示/隐藏错误div。

HTML代码:

  

CSS:

  .error { color: red; } 

JS代码:

 //hide error before ajax call $('.error').hide(); $.ajax(...) .done:function(){ ... } .fail: function(jqXHR, textStatus, errorThrown){ $('.error').text(errorThrown); $('.error').show(); } 

注意: .success().error()方法在jquery 1.8中已弃用,因此请避免使用它们。

弃用注意:自jQuery 1.8起,不推荐使用jqXHR.success(),jqXHR.error()和jqXHR.complete()回调。 要准备最终删除的代码,请改用jqXHR.done(),jqXHR.fail()和jqXHR.always()。

在你的捕获中你可以放

 header('Content-type: application/json'); echo json_encode(array('Error' => 'PDO fel "$err"')); 

请尝试使用以下代码段:

 var x = ($(this).text()); $.ajax({ type: 'POST', url: 'process.php', data: { text1: x }, success: function(response){ $('#tooltip').text(response); }, error: function(error) { console.log(error); } }); 

在数组上使用PHP函数json_encode。 然后,该数组将作为JSON对象(’response’参数/参数)呈现给javascript。

换一种说法:

PHP:

 // important to tell your browser what we will be sending header('Content-type: application/json; charset=utf-8'); ... bla bla code ... // Check if this has gone right $success = $results->execute(); $row = $results->fetch(); $html = $row[0]; $result = [ 'success' => $success, 'html' => $html, ]; print json_encode($result); 

JavaScript的:

 // You may now use the shorthand $.post('process.php', { text1: x }, function(response) { if (response.success) { $('#tooltip').text(response.html); } else { ... show error ... } }); 

首先 ,你需要知道javascript服务器端有错误

 try { $db = new PDO('sqlite:ordbas.db'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $err) { // Set http header error header('HTTP/1.0 500 Internal Server Error'); // Return error message die(json_encode(array('error' => 'PDO fel '.$err->getMessage()))); } 

其次 ,你需要在加载json时处理错误

 var x = ($(this).text()); $.ajax({ type: 'POST', url: 'process.php', data: { text1: x } }) // This will be called on success .done(function(response){ $('#tooltip').text(response); }) // This will be called on error .fail(function(response){ // Error catched, do stuff alert(response); }); 
 $.ajax({ url: "file_name.php", method: "POST", data: $("#form_id").serialize(), success: function () { alert("success"); //do something }, error: function () { alert("doh!"); // do something else } }); 

这是处理敏感表单数据(或者您将绑定到UPDATE或INSERT查询的数据)的POST请求的示例。 我包含了serialize()函数,以便处理后端表单中的名称字段。 我还删除了通过success函数传递数据。 在处理您不打算显示的敏感数据或数据时,您不希望这样做。 想我会在这里发布这个,因为当我搜索如何使用返回错误的AJAX进行POST时,这个线程出现了。

说到返回一个错误,你现在想要这样做,因为PHP已经再次更新。 我还建议阅读5.4+文档。

 http_response_code(404); die(); 

我投入了die()函数,以确保在请求404之后没有其他任何事情发生。