我有以下功能:
side= 'car';
var request_checkUrl = '/antibot/antibot_data?script=' + side;
$.ajax({
url: request_checkUrl,
dataType: 'application/json',
complete: function(data){
alert("running..");
},
success: function(data){
alert("success");
},
error: function(data) {
alert("ERROR");
console.log(data);
}
})
结果是: 带有错误的框,然后运行。它还在控制台日志中显示这一点:
响应是正确的。但是,为什么这段代码在应该成功的情况下却向我抛出错误消息?
我也尝试过使用 get、getjson、ajax 和数据类型 json 等,但我得到了相同的结果。
我在这里做错了什么?
编辑:
以下是完整回复:
{
"status": 200,
"data": {
"text": "en TV",
"images": [
{
"hash": "47a32df0c4b1f0b522e5faf35a46aacd95fe0ed4",
"file": "ABImage_plane_1"
},
{
"hash": "e11f83f4411364546329c8a8bf88da0dffd27029",
"file": "ABImage_house_2"
},
{
"hash": "93b4454ac09e7d7478fa2d25322e0e784370ea7a",
"file": "ABImage_car_5"
},
{
"hash": "36fac21a830b922edb507487d833556aeb9688f7",
"file": "ABImage_clock_4"
},
{
"hash": "cd1df47e052a5d0d50dab61b3e716339be0c6e68",
"file": "ABImage_TV_3"
},
{
"hash": "59e7f70b7874a500e576e25077adf254c52f5ee8",
"file": "ABImage_train_4"
}
]
}
}
编辑2:
这是我使用服务器端 PHP 的功能
echo $this->framework->ajaxJSONResponse(200, $data);
和
function ajaxJSONResponse($status, $data) {
header('Content-type: application/json');
$response = array();
$response['status'] = $status;
$response['data'] = $data;
return json_encode($response);
}
编辑: 我使用 jquery 2.1.3
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
编辑: 我也尝试过:
$.ajax({
url: request_checkUrl,
type: "GET",
dataType: "json", // "xml", "json"
success: function (data) {
alert("success");
alert(data);
},
error: function (jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
输出错误:
再次更新:
我尝试使用以下方法验证网址: http://www.freeformatter.com/json-validator.html
得到:
The JSON input is NOT valid according to RFC 4627 (JSON specification). Unexpected token {"status":200,"data":{"text":"en TV","images":[{"hash":"47a32df0c4b1f0b522e5faf35a46aacd95fe0ed4","file":"ABImage_plane_1"},...
但是如果我启用:
Accept non-quoted names
我明白了:
The JSON input is valid according to RFC 4627 (JSON specfication).
我怎样才能按照我的要求完成这项工作?
最佳答案
以下答案只是尝试帮助找到可能的解决方案。
尝试将您的代码修复为如下所示:
var side = 'car';
var request_checkUrl = '/antibot/antibot_data?script=' + side;
$.ajax({
url: request_checkUrl,
type: "GET",
dataType: 'json',
beforeSend: function () {
document.title = "Running...";
},
success: function (data) {
document.title = "Success.";
alert("success");
},
error: function (data) {
alert("ERROR");
console.log(data);
}
});
请告诉我这是否有效。
更新:
在上次更新中,您得到了无效的 json。由于 PHP,您始终需要打印有效的 json。您可以使用此链接来验证您的 json 输出:http://pro.jsonlint.com .
parsererror, SintaxError: Unexpected token
: 这意味着,你的 php 代码有问题。
关于javascript - ajax 抛出错误并得到正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33069713/