anh pham anh pham - 1 year ago 91
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 ( == 200) {
var resp = JSON.parse(;
if (resp.status == 'success') {
} else {
xmlHttpRequest.onload = function () {};"POST", "", true);

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

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(; --> 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 Source

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:

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


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

Hope this helps