Reputation: 847
Here's my ajax call:
function fetchAccount(email, callback) {
$.ajax({
url: "http://example.com/",
jsonp: "callback",
dataType: 'jsonp',
type: 'GET',
async: false,
headers: {"Accept" : "application/javascript; charset=utf-8"},
success: function(data) {
appState.user = data;
appState.viewState = AppStates.CONTENT_VIEW;
AppStore.persistToLocalStorage();
callback();
},
error: function(xhr, status, err) {
appState.user = "";
appState.viewState = AppStates.LOGIN_FAIL_VIEW;
AppStore.persistToLocalStorage();
callback();
}
});
};
My server isnt returning JSONP because the accept header isn't actually set properly. When I use the "modify headers" google chrome extension to manually inject "Accept" "application/javascript; charset=utf-8" the server responds with JSONP just fine.
I captured the request header and as expected, "Accept" isnt being set properly:
GET /api/accounts/[email protected]?callback=jQuery22009572079558856785_1454040030107&_=1454040030108 HTTP/1.1
Host: www.example.com
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,et;q=0.6
What's going on here - how can I get it to properly set the accept header? It seems so simple...
Upvotes: 1
Views: 946
Reputation: 847
The problem is that i'm expecting the wrong thing. According this this jquery bug report (https://bugs.jquery.com/ticket/7694) when you do JSONP you're not actually firing an XHR so you can't control the headers.
Upvotes: 1
Reputation: 532485
When you request JSONP
you are asking for a script to be sent back that executes the callback you are giving it. The proper Accepts header for a script would be application/javascript
not application\json
. Seems to me that your server is the one in the wrong here, not jQuery. That said, you could try setting the accepts
property in the AJAX settings to application/json
and see if that works. I do not think that should be necessary nor would I recommend it even if it works; I would suggest you fix the server if possible.
From the jQuery,ajax API docs:
If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.
Upvotes: 0