简体   繁体   中英

Ajax success function not working with returned json data and status 200/304

I'm making an AJAX call that returns a JSON object, and is successfully the JSON in browser. However, the success function isn't fired but rather the error block is hit with the message only saying "error" which isn't much to go on. The status is either 200 or 304 and I can see the object on the network in developer tools so it's there but I can't access that object in the success function.

Here is the ajax call:

$.ajax({
    type: "get",
    dataType: "json",
    jsonp: "false",
    url: "http://my.api.url:8080/quote",                                                                                          
    success: function(r){
        var q = r;
        $("#quote").append(q);
},
    error: function(xhr, status, error) {
        console.log(xhr);
    }
});

The JSON:

{"msg":[{"quote":"quote goes here"}]}

The JSON is generated by an express/node application with response.json() if that effect things, I'm relatively new to those. I have tried setting the jsonp to false, using contentType: 'application/json; charset=utf-8', over datatype json, among other ineffective tries. Any help/critiques are appreciated.

So the problem here is actually CORS,cross origin resource sharing, since jQuery is calling the API from a different port CORS was blocking the resulting JSON data as per the safety standard. A simple middleware addition to the node.js app adjusting the headers for dealing with CORS solves the problem eg

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type, Accept");
    next();
});

So the json was essentially in the browser but inaccessible to any scripts because of the headers. These pages helped a lot should someone else encounter this problem.

Enable Cors
Mozilla Dev

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM