Will
Will

Reputation: 681

$.ajax call fail with dataType is json

I would like to send an ajax call to a JSON file to retrieve the data. But ajax call failed with dataType: "json". When i change dataType to "text", ajax call successfully.

below is the code:

$.ajax({
    type: "POST",
    url: url,
    dataType: "json",
    success: function(response) {
        console.log("success");
    },
    error: function() {
        alert("failed");
    }
});

the JSON file is:

{
 "mobile": [{"中国": ["1", "2", "3", "4", "5", "6"]},
            {"美国": ["3", "5", "10", "20", "30", "50"]}
           ],
 "uni": [{"德国": ["5", "10", "20", "30", "50"]},
         {"英国": ["30", "50", "00", "20", "50"]}
        ],
 "telcom": [{"法国": ["10", "20", "30", "50", "00", "500"]}
           ]
}

Upvotes: 1

Views: 2242

Answers (2)

VMAtm
VMAtm

Reputation: 28355

JSON you've provided is a valid one, so I think the error is in other place.
You can use the multiple values space-separated into dataType setting, like this:

dataType: "text json",

So jquery will get the result as text and after that interpret it as JSON.

In comments you're saying that there are some chinese characters, try to encode them in Unicode.

Upvotes: 1

user3310334
user3310334

Reputation:

That's because the data type is not JSON, but rather application/json. Try

    dataType: "application/json"

but if that doesn't work, you can always use a dataType of text, and JSON.parse it afterwards, as that's all JSON is anyway.

Upvotes: 1

Related Questions