Vinay Jeurkar
Vinay Jeurkar

Reputation: 3122

Get HTML of another page in another domain using JavaScript

Right now, I am using curl in PHP to get the HTML source code of some remote web page.

Is there any way I can get the same HTML source code of some cross-domain web page in JavaScript? Any tutorials?

Upvotes: 1

Views: 14644

Answers (3)

Amr Elgarhy
Amr Elgarhy

Reputation: 69012

I think you need to know about JSONP to access cross-domain web pages in js

https://stackoverflow.com/questions/tagged/jsonp?sort=votes

Upvotes: 2

David
David

Reputation: 3441

This solution I just found might be of use like the other workarounds...

http://www.ajax-cross-domain.com/

Upvotes: 0

Bosh
Bosh

Reputation: 8758

Q. How is this any different than issuing an AJAX "GET http://otherdomain.com/page.html" call?

A. The same-origin policy checks the HTTP response headers for AJAX requests to remote domains, and if they don't contain a suitable Access-Control-Allow-Origin header, the request fails.

So, there are two ways to make this work:

  • If you control the other domain, you can include the following header in the HTTP response:

    Access-Control-Allow-Origin: *
    (details at MDC)

  • If you don't, you're stuck implementing a server-side proxy (for example, this simple PHP proxy).

In any case, once you implement one of the two options above, you're left with a simple AJAX call:

$.ajax({
  url: "http://mydomain.com/path/to/proxy.php?url="+
        encodeURI("http://otherdomain.com/page.html"),
  dataType: "text",
  success: function(result) {
    $("#result").text(result);
  }
});

Upvotes: 0

Related Questions