Reputation: 13620
I've some problems getting som JSON data from my webhost. So no I have broken down the function only to GET google, and it still does not retrieve the data. Nothing happens, I've added the function below to a button in the app (onclick, return false yada yada):
loadGoogle: function () {
console.log('Lets load Google!');
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
type: 'GET',
contentType: 'text',
url: 'http://google.com'
})
.done(function (data) { console.log('GOOGLE IS LOADED'); })
.fail(function (xhr, error, et) { console.log('GOOGLE WAS NOT LOADED'); });
console.log('The end');
}
the output in console during emulating:
CommandString : DebugConsole/log/DebugConsole1659732817/"Lets load Google!"
Log:["Lets load Google!","DebugConsole1659732817"]
The thread 0xfb0 has exited with code 259 (0x103).
CommandString : DebugConsole/log/DebugConsole1659732818/"The end"
Log:["The end","DebugConsole1659732818"]
The thread 0xff4 has exited with code 259 (0x103).
As you can see It output the log
before AND after the ajax, but not the done
or fail
events triggers. And as you see I have enabled cors and allowCrossDomainPages according to the doc. So why am I failing at this? Google is not the source I want to read, but I cant even get that to work so...
Upvotes: 0
Views: 128
Reputation: 93
You can use Jsonp instead of Json and you should have no issues:
$.ajax({
type: "POST",
url: 'http://DomainName.com/api.php',
dataType: 'jsonp',
contentType: "application/json",
cache: false,
success: function(data)
{
// append your data
}
Upvotes: 0
Reputation: 4023
You can use a proxy to route the calls to Google through your web server. If you are using Microsoft IIS, you can use the URL rewrite module as I describe here cross domain AJAX using proxy. If using Apache, you can use mod_proxy to redirect cross domain calls through your website's server.
This might not be ideal, but it might be a reasonable solution for you.
Upvotes: 0
Reputation: 1075925
And as you see I have enabled cors...
It's not up to you to enable CORS (for other people's sites). For you to retrieve data from google.com
, they have to enable CORS and allow your origin to extract data from them. (There's a wildcard, *
, if they want to allow everyone to load their content.)
Also note that the browser has to support CORS. All up-to-date modern desktop browsers do, as do most mobile browsers, although note that both IE8 and IE9 require that you use the non-standard XDomainRequest
object, not XMLHttpRequest
(they finally get this right in IE10), and jQuery does not smooth over that particular cross-browser issue for you (does not, and will not). There are plug-ins that do, though.
If you're in control of the remote end (e.g., the webhost you're retrieving data from), then you can enable CORS at the server level by responding to the preflight call and the GET
with the appropriate response headers.
More:
Upvotes: 2