You can't load external files with AJAX. However, you can set up a file on your own server that makes the content available on your server. For instance in PHP, you could write a file googlexml.php
:
<?php
@readfile("http://www.google.com/cse?cx=MY_UNIQUE_KEY&client=googlecsbe&output=xml_no_dtd&q=query+terms");
?>
And then you could access that with AJAX. I'm not sure if Google's terms of use will let you do that, but if they do, then this is an option.
Browsers do not allow cross-domain AJAX calls. Only cross-domain JSONP requests are allowed.
To use JSONP requests, you have to change the dataType
property to jsonp
. This means however you can not request XML, but JSONP only.
A bit about JSONP:
The <script>
tag bypasses the cross-domain limitations. Which means that you can use that tag to get data from other servers. That tag doesn't support all kinds of languages, hence XML is not supported.
JSONP is basically JSON, but with a function call around it like this:
functionname({"property":"value"})
I can see you wondering: "What is that functionname doing there?"
That's EXACTLY the difference with JSON. Because the function is wrapped around it, you can use the actual data!
<script type="text/javascript">
var functionname = function(json) {
alert(json.property);
}
</script>
<script type="text/javascript" src="http://www.domain.com/jsonp"></script>
If you replace the second script tag with the response content, it'll all make sense:
<script type="text/javascript">
var functionname = function(json) {
alert(json.property);
}
functionname({"property":"value"});
</script>
Believe it or not, but this minor difference actually enables us to make cross-domain requests much safer.
Another thread about JSONP
Best Answer
No way to load XML. So yes, using "standard" xmlhttprequests you need JSONpadding.
If the server supports "Cross-Origin Resource Sharing (CORS)" you can easily receive data from a foreign domain. That means, you have to add a custom header into your XmlHttpRequest ('Origin') and the server decides if it does allow the request or not.