Is there a way to load an XML file from another domain using only JavaScript?

jQuery has a $ .getJSON () function that I use to load json files from other domains, for example:

$.getJSON('http://somesite.com/file.js', function(output) {
   // do stuff with the json data
});

I was wondering if I can do the same with xml files from other domains, or do I need to use the server language for this?

This is the xml document I would like to download:

http://google.com/complete/search?output=toolbar&q=microsoft

+5
source share
3 answers

I agree with @viyancs, simply saying, if you want to get xml of another domain, there is a cross-domain restriction, the way to solve this is to create a proxy server, so the request process:

1. $.ajax, ( URL- xml, ).

2. URL- xml.

3. $.ajax.

: http://developer.yahoo.com/javascript/howto-proxy.html

: JSON? , JSONP.

+2

$.ajax({
   type: "GET", 
   dataType: "xml", 
   url:"localhost/grab.php", 
   success: function(){
    //to do when success
   }
 });

1) URL- grab.php:

<?php
   $url = 'http://google.com/complete/search?output=toolbar&q=microsoft';
   $parsing = parse_url($url);
   $scheme =  $parsing[scheme];
   $baseurl = basename($url);
   $strbase =$baseurl;
   $finalUri = $scheme .'://' .$strbase;
   $handle = fopen($finalUri, "r",true);
    // If there is something, read and return
 if ($handle) {
  while (!feof($handle)) {
   $buffer = fgets($handle, 4096);
   echo $buffer;
  }
  fclose($handle);
 }

? >

0

If you really don't have the ability to use a proxy server with a cache (which is a proper ethic), you can use something like YQL as a JSONP proxy service . Ultimately, you will reach the limit without an API key.

// query: select * from xml where url='http://google.com/complete/search?output=toolbar&q=microsoft'
var xml_url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fgoogle.com%2Fcomplete%2Fsearch%3Foutput%3Dtoolbar%26q%3Dmicrosoft'&diagnostics=true"
$.get(xml_url,function(xml){ console.log(xml); });
0
source

All Articles