我有'意外字符错误'的问题,我的Jquery ajax代码看起来像这样:
function test(){
if(true){
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'json',
data: {
godot: 'godot',
jobadze: 'jobadze'
},
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) { alert("Error Status: "+textStatus+"'nMessage: "+errorThrown);
}
});
,这是PHP代码:
<?php
echo 'test';
?>
应该提示"test",但是它调用了error。发生了什么事?
没有返回任何JSON。返回文本,但AJAX中指定返回json。
你有:dataType: 'json',
如果总是返回文本
,则可以更改dataType: 'text',
或在您的php更改echo 'test';
为echo json_encode('test');
希望能有所帮助
您编写了dataType: 'json'
,因此PHP脚本需要返回有效的JSON。因为不是,所以当它试图将响应解析为JSON时,它会得到一个错误,并报告该错误。
你应该使用json_encode
:
<?php
echo json_encode('test');
?>
它应该提示"test",但是它调用了error。发生了什么事?
原因是你的dataType : "json"
在$.ajax()
方法中,它期望服务器端的响应应该是json
,事实并非如此,因为这只是一个简单的文本字符串,没有别的,所以你能做什么:
- 删除
dataType
或更改dataType: "text"
- 或者在服务器端做一个
json_encode('string')
。
如你在问题中所问
提示"test",
所以你可以跳过#2,这样做:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'text',
data: {
godot: 'godot',
jobadze: 'jobadze'
},
success: function(data){
alert(data); // will alert "test".
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error Status: "+textStatus+"'nMessage: "+errorThrown);
}
});
但是会调用error
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'json', //<----because of this
看json
是一个{key : value}
对js对象,从你的php
你只是回显字符串而不是对象。