这是我的Ajax呼叫代码:
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'ajax.php',
cache: false,
data: { json : JSON.stringify({
name:name,
email:email,
password:password
})},
dataType: 'json',
success: function(){
alert('request successful');
},
error: function(){
alert('error occured');
}
});
请求状态为200,但错误函数始终被调用。
有人知道吗,
最有可能的问题是,在这行中:dataType: 'json',
因为它期望Json响应,并且您正在发送html或文本文本响应。让我们先来看一下定义:
JSON.stringify将Javascript对象转换为JSON文本,并将该JSON文本存储在字符串中。
contentType是发送到服务器的标头,指定特定格式。
dataType是告诉jQuery期望什么样的响应。
例子:
如果您要发布类似的信息{"name":"John Doe"}
:{"success":true}
然后,您应该具有:
var data = {"name":"John Doe"};
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
有关更多详细信息:检查jQuery Docs
解决方案1 :(已测试)
dataType: 'json',
行,然后让jQuery确定数据类型即可。(在识别方面做得很好)或确保在两侧(客户端和服务器)使用正确的dataType解决方案2 :(经过测试)
jQuery的:
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType : "html", //assuming you need html response like '<div>Success</div>'
//Common types: html, xml, json & text
cache: false,
data: { json : encodeURIComponent(JSON.stringify({
name:name,
email:email,
password:password
}))},
success: function(){
alert('request successful');
},
error: function(){
alert('error occured');
}
});
PHP:
$json_data = json_decode(urldecode($_POST['json']));
//now $json_data variable has decoded JSON data
echo $json_data->name;
解决方案3 :(未经测试)
通过设置发送JSON对象contentType
:
contentType: "application/json; charset=utf-8",
然后使用读取原始输入php://input
(注意:$_POST
在这里不起作用)
就是这样:
header('Content-Type: application/json; charset=UTF8');
$input = file_get_contents('php://input');
$decoded_input = urldecode($input);
$data = json_decode($input);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句