anh pham anh pham - 3 months ago 25
JSON Question

{Javascript} How to return Json when calling POST xmlHttpRequest

I tried to use xmlHttpRequest POST to upload file in Meteor project. With Django REST framework 2.3.14.

I used:

var file = $('#control_import_file')[0].files[0];
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function (e) {
if (e.target.status == 200) {
var resp = JSON.parse(e.target.response);
if (resp.status == 'success') {
alert("success");
} else {
alert("fail");
}
}
};
xmlHttpRequest.onload = function () {};

xmlHttpRequest.open("POST", "http://mydemosite.net/orders/import-coupon/25/", true);

if (window.FormData) {
var formData = new FormData();
formData.append("datafile", file);
xmlHttpRequest.send(formData);
}


In Chrome, it returns:


Event {isTrusted: true, type: "readystatechange", target:
XMLHttpRequest, currentTarget: XMLHttpRequest, eventPhase: 2…}


So I can easyly get Json string: target.response object:


""{"status": "error", "data": {"error_data": ["test123"],
"error_code": 0, "error_msg": "Check failed"}, "error_data":
["test123"], "error_code": 0, "error_msg": "Check failed"}"


JSON.parse(e.target.response); --> get sth I want.

However in Firefox: it returns all that json string above in HTML format:

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><meta name="robots" content="NONE,NOARCHIVE"...</html>


Anyone can help me how to handle error response in Firefox? Or Is there any way to get response in all browsers?
Thanks a lot!

Answer

Django Rest Framwork checks the "Accept" header to define if he must return HTML, JSON, CSV or any other format that he can render (cf: http://www.django-rest-framework.org/api-guide/renderers/)

since you are manually using XMLHttpRequest, try adding the accept header with setRequestHeader. Something like:

xmlHttpRequest.setRequestHeader("Accept","application/json");

check in your console that you are passing the correct headers on Chrome and Firefox

Hope this helps