我正在使用返回JSON的API。 API返回的JSON语法被破坏,我无法控制它来修复它。
我正在使用JQuery Ajax调用,它返回 500 - 内部服务器错误。我想获得API响应和纯文本并修复JSON语法。它只有一个额外的逗号,我可以删除。但我无法以明文形式得到答复。
我尝试了几种方法,例如使用dataType将纯文本设置为纯文本的内容类型和/或接受标题,如下所示。我的代码如下。
$.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 从浏览器或提琴手直接调用时,API工作正常。这就是我如何知道JSON语法被破坏的原因。
答案 0 :(得分:4)
$.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作为字符串返回。
答案 1 :(得分:0)
$.ajax({
// the URL for the request
url: apiUrl + "/" + customerId + "/accounts/" + accountId,
// the data to send (will be converted to a query string)
data: "client_id=" + clientId,
// whether this is a POST or GET request
type: "GET",
// the type of data we expect back
//Use JSON so that the browser knows how to format and transfer the data correctly, you
//can always converted to plain text once you receive it
dataType: 'json',
async: true,
// code to run if the request succeeds;
// the response is passed to the function
//output everything to the console to inspect the response that way you can see everything
//the API sends back. I'm assuming you know how to Inspect Element and look at the Console
//on your browser
success: function( response ) {
console.log(response)
},
// code to run if the request fails; the raw request and
// status codes are passed to the function
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
// code to run regardless of success or failure
complete: function( xhr, status ) {
console.log(xhr, status)
}
});
答案 2 :(得分:0)
你说
jqXHR状态为0且未显示错误消息
和
我复制了此请求的开发者工具中的网络选项卡中显示的网址,并直接在浏览器上进行了尝试,它给了我json响应。
在您的评论中,这让我相信这是您在服务器端遇到的500 - Internal Server Error
之上的CORS问题。
如果您希望以纯文本形式获取服务器响应(并且您可以以某种方式设置您的API请求以避免500错误),那么使用服务器端wrapper/proxy(或PHP + cURL)从第三方网站获取您的数据作为文本,过滤或以其他方式修复它,然后eval()
它(风险自负)作为正确的JSON对象。