Reputation: 201
jQuery:
$.ajax({
url : url,
type : 'GET',
dataType: 'json',
data: {
'FN' : 'GetPages',
'PIN' : '7659'
},
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function(data) {
alert('succsess');
console.log('data', data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error');
console.log(xhr.status);
console.log(thrownError);
}
});
Firebug Firefox Network
What happens
The AJAX "error:" event gets triggered and my console.log outputs are:
xhr.status -> 0
thrownError -> (empty String)
Is this normal? When I type the URL in a browser I receive a file download with the JSON content in it, this shouldn't be a problem right?
Upvotes: 6
Views: 28053
Reputation: 1590
In my case status "200 OK", but no data was due to Django settings:
CORS_URLS_REGEX=r"^/api/.*$"
but my url did not start with /api/. So I need to add my url to CORS_URLS_REGEX expression or comment it out.
Upvotes: -1
Reputation: 175
I cant figured out from the image, but if you are trying send AJAX request to different domain, you need to use JSONP, simple AJAX request will not be sufficient
Try to change dataType: 'json'
to dataType: 'jsonp'
and add callback=?
to your URL
Upvotes: 2
Reputation: 201
Thanks to @CrimsonChin I know its a Same Origin Policy problem
In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.[1]
(from http://en.wikipedia.org/wiki/Same_origin_policy)
Granting JavaScript clients basic access to your resources simply requires adding one HTTP response header, namely:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://foo.example.com
(from http://enable-cors.org/)
Ofc, turning the JSON response into a JSONP response would also work. Thx @djakapm
Upvotes: 10
Reputation: 151
Try this one
$.ajax({ type : "GET",
url : URL,
data: {
'FN' : 'GetPages',
'PIN' : '7659'
},
xhrFields: {
withCredentials: true
},
crossDomain: true,
dataType : "jsonp",
jsonp : "jsoncallback",
jsonpCallback : "SMS",
cache : true,
success : function(service_data) {
},
error : function(msg) {
alert(JSON.stringify(msg));
}
});
Upvotes: 3