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

本文探讨了在处理AJAX请求时遇到错误警报的问题,重点在于MySQL查询的执行和返回JSON数据的正确格式。作者提供了从使用PDO替换过时的mysql_函数,到正确设置Content-Type和检查查询结果的详细步骤,并给出了客户端和服务器端的代码示例。
摘要由CSDN通过智能技术生成

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

客户方:

$(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;

});

});

服务器端:

$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);

?>

考虑使用pdo,mysql_函数已经过时了

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

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!");

}

},

希望能帮助到你。

哦,你应该区分服务器端错误和传输错误。 我检查了AJAX的success部分来检查服务器发送的值(因此它不是传输错误)。

如何存储多个变量,如$ response_array ['status'] ='成功',$ response_array ['userid'] = $ userid; 等等

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

error:function(x,e) {

if (x.status==0) {

alert('You are offline!!

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.

Parsing JSON Request failed.');

} else if(e=='timeout'){

alert('Request Time out.');

} else {

alert('Unknow Error.

'+x.responseText);

}

}

大! 刚发现我的服务器不支持json_encode

@Pieter:然后实现自己的js_encode :)试试这个:snippets.dzone.com/posts/show/7487

有些人建议使用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);

然后在您的客户端代码中

if (!data.error) {

... got data, do something with it ...

} else {

... invoke error handler ...

}

要构建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:

"+responseText.messages);

}

});

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

//...

//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!");

}

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

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

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

添加到顶部答案:这里是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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值