我正在使用返回 JSON 的 API。 API 返回的 JSON 语法已损坏,我无法控制修复它。
我正在使用 JQuery Ajax 调用,它返回500 - 内部服务器错误。我想要获取 API 响应和纯文本并修复 JSON 语法。它只是在末尾多了一个逗号,我可以将其删除。但我无法获得纯文本形式的响应。
我尝试了多种方法,例如使用 dataType 将内容类型和/或接受 header 设置为纯文本,如下所示。我的代码如下。
$.ajax({
url: apiUrl + "/" + customerId + "/accounts/" + accountId,
data: "client_id=" + clientId,
dataType: 'text',
type: 'GET',
async: true,
statusCode: {
404: function (response) {
console.log('Invalid Transaction details');
},
200: function (response) {
//response processing code here
}
},
error: function (jqXHR, status, errorThrown) {
//Error handling routine
}
});
更新 1 当直接从浏览器或 fiddler 调用时,该 API 工作正常。这就是我知道 JSON 语法已损坏的原因。
最佳答案
你的代码运行良好,肯定还有另一个错误
$.ajax({
url: 'http://ip.jsontest.com/',
dataType: 'text',
type: 'GET',
async: true,
statusCode: {
404: function (response) {
alert(404);
},
200: function (response) {
alert(response);
}
},
error: function (jqXHR, status, errorThrown) {
alert('error');
}
});
它从测试 API 返回 json 作为字符串,一切正常。
关于jquery - 如何使 JQuery 将 Ajax 响应视为纯文本而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26384375/