我一直收到错误警报。 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);