如何使JQuery将Ajax响应视为纯文本而不是JSON

the*_*ark 13 ajax jquery

我正在使用返回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
    }
});
Run Code Online (Sandbox Code Playgroud)

更新1 从浏览器或提琴手直接调用时,API工作正常.这就是我如何知道JSON语法被破坏的方式.

Tua*_*uan 5

您的代码运行良好,必须有另一个错误

看我的小提琴

$.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');
    }
});
Run Code Online (Sandbox Code Playgroud)

它从测试 API 返回 json 作为字符串,一切都很好。


小智 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)
}
});
Run Code Online (Sandbox Code Playgroud)