tags:

views:

118

answers:

6

Greetings, how can I download some page content using ajax and jquery: I am doing something like that (2 versions inside one script):

$("p").click(function() {

    $('#result').load('http://google.com');

            $.ajax({
                url='www.google.com',
                success: function(data) {
                    $("result").html(data);
                    alert('Load was performed.');
                    var url = 'www.wp.pl';
                    $('div#result').load(url);
                    //var content = $.load(url);
                    //alert(content);
                    //$("#result").html("test");
                }
            });
});

but it does not return any content

+3  A: 

Due to restrictions you cannot download the contents of a web page using AJAX that is not hosted on the same domain as the domain hosting this script. Also you have a syntax error in your .ajax function call. It should look like this:

$.ajax({
    url: 'http://yourdomain.com/page1.htm',
    success: function(data) {
        $("result").html(data);
        alert('Load was performed.');
        var url = 'http://yourdomain.com/page2.htm';
        $('div#result').load(url);
    }
});
Darin Dimitrov
is there any way to do this? to get the content of other page?
niao
you can display the content of another page within an iFrame, but you can't access/read it either.
jAndy
Take a look at my answer - it provides a couple of methods to retrieve data external to the current domain.
Seidr
+1  A: 

While it is not possible to directly query a host that is external to the current domain from Javascript, you could use a proxy script to retrieve the desired data.

Cross domain AJAX querying with jQuery: http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html

You could also make use of the flXHR script, which can be dropped into many Javascript libraries (including jQuery).

flXHR: http://flxhr.flensed.com/

Seidr
A: 

you 'could' do that with

$('#element').load('sites/test.html #content');

for instance. But in your example, you try to access another domain which is not allowed due to the ajax same origin policy.

Kind Regards

--Andy

jAndy
+1  A: 

You could also simply call a PHP/ASP/RUby page that in turn does the outside calling for you and presents the information in a way that you need.

1.  PAGE --> PHP --> External web
        (Ajax)

2.  PAGE <-- PHP <-- External web
      (callback)
WmasterJ
+2  A: 

You could use YQL to proxy your call:

$.ajax({
  url:"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'http://www.google.com'&amp;format=xml&amp;callback=callback",
  type: 'GET',
  dataType: 'jsonp'
});

  function callback(data){
    $('#result').html(data.results[0]);
  }
Pavlo
+1  A: 

You need to use something called JSONP to go across domain. Seider has psoted more details on how to do this with jQuery.

James Westgate