ajax如何从PHP文件返回错误消息 [英] ajax how to return an error message from a PHP file
本文介绍了ajax如何从PHP文件返回错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我将鼠标悬停在任何单词上时,总是显示一个黑框.如果PHP代码返回文本,它将显示在黑框中(应该显示).但是,如果文本未返回,我希望它返回一个错误函数,以便以后可以更改黑框的CSS,以使其宽度为0px
而不是400px
.
At the moment when I hover over any word a black box is always showing. If the PHP code returns text it is displayed in the black box (which it should). However I want it to return an error function if the text is not returned so I can then later change the CSS for the black box so that it has a width of 0px
instead of 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];
}
您可能已经发现,我遗漏了一些不重要的代码.希望有人能理解和帮助我!谢谢!
As you might have figured out there is some non-important code that I left out. I hope someone can understand and help me! Thanks!
推荐答案
以下正是您的操作方法:
Here is exactly how you can do it :
在您的PHP文件中:
if ($query) {
echo "success"; //anything on success
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
在您的jQuery AJAX端:
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====
}
});
这篇关于ajax如何从PHP文件返回错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文