Jquery AJAX从PHP返回 [英] Jquery AJAX return from PHP

查看:84
本文介绍了Jquery AJAX从PHP返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此Jquery AJAX方法的新功能。所以我正在使用Jquery进行AJAX调用,在我的PHP脚本中,我在从数据库中检查条件为真,然后传入我的数据字符串并绑定变量,然后执行该查询。脚本和数据库插入都正常工作。

New to using this Jquery AJAX method. So i'm making an AJAX call with Jquery, In my PHP script i'm checking a condition to be true from my Database, before I pass in my datastring and bind the variables, then execute that query. Both the script and Database insert work correctly.

我的问题是,如何从我的PHP脚本返回时在AJAX调用中显示错误消息?

My question is, how can I get it to display the error message in my AJAX call on return from my PHP script?

JS

$.ajax({
type: "POST",
url: 'submit_form.php',
data: dataString,
error: function() { alert('Error'); },
success: function() { alert('Success'); }
});



SUBMIT_FORM.PHP



SUBMIT_FORM.PHP

if ( count of rows in db < x  )
 {

return false;
exit();

}




如果此条件为真我想停止执行我的脚本并在我的AJAX函数中执行
错误条件。

if this condition is true I want to stop execution of my script and execute the error condition in my AJAX function.







elseif ($stmt = $mysqli->prepare("INSERT INTO blah (stuff, morestuff) values (?, ?)")) {

 /* Bind our params */
  $stmt->bind_param("ss", $param1, $param1);

        /* Set our params */
$param1= $_POST["name"];
$param2= $_POST["email"];


/* Execute the prepared Statement */
$stmt->execute();
/* Close the statement */
$stmt->close(); 
}




如果第一个条件为假则我想要返回我目前正在进行的ajax调用中的成功函数。

if the first condition is false then I want to return the success function in my ajax call which it is currently doing.


推荐答案

要调用您的 $。ajax 的错误处理程序,您可以在PHP中编写以下代码(对于FastCGI):

To invoke the error handler of your $.ajax, you can write the following code in PHP (for FastCGI):

header('Status: 404 Not found');
exit;

或者,使用标题('HTTP / 1.0 404 Not Found')如果您没有使用FastCGI。

Alternatively, use header('HTTP/1.0 404 Not Found') if you're not using FastCGI.

我个人不会使用这种方法,因为它模糊了Web服务器错误和应用程序错误之间的界限。

Personally I wouldn't use this approach, because it blurs the line between web server errors and application errors.

你最好使用如下错误机制:

You're better off with an error mechanism like:

echo json_encode(array('error' => array(
    'message' => 'Error message',
    'code' => 123,
)));
exit;

在成功处理程序中:

if (data.error) {
    alert(data.error.message);
}

这篇关于Jquery AJAX从PHP返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆