views:

59

answers:

2

Hi,

I have a url and I want to retrieve the html dom generated when going to the url (all the code for the page) in a javascript variable.

How can I do this? I'm guessing an html get or post? Can anyone give an example with jQuery?

Every time I do a $.get or $.post like this:

$.get("http://www.google.ca", function(result) { alert(result); alert($(result).html()); });

$.post("http://www.google.ca", function(result) { alert(result); alert($(result).html()); }, "xml");

the first alert in each call comes up blank and the second comes up as null. Any ideas?

Thanks,
Matt

A: 

You can only fetch documents (in this way) from your own domain due to the same origin policy.

Laurence Gonsalves
I've definitely done it before... just can't remember exactly how. This one site I post to returns a generated page as the response, so I think it's a post... I just keep getting null returned for some reason. Same origin policy doesn't apply, all I want is to pull in the html dom so I can search through the dom and pull information i'm searching for.
Matt
The only thing you can pull from a different origin in javascript is javascript. For html you can't fetch from a different domain. If you could then no one would be safe from xsrf. If you ever had this working it was probably in a local file that your browser considered to be "trusted". The standard workaround is to have your server act as a mediator. ie: your client code asks your server to fetch the page you want. That works since your server is the same origin as your js.
Laurence Gonsalves
what about in back end code? If I did it in C#? Because last time I did it I believe it was with php... which is back end code isn't it?
Matt
On your server you can fetch from whatever URL you want. So, yeah, if by "back end code" you mean code running on your server, it'll work there. C# or PHP or whatever should be fine, as long as it isn't running in the browser. (That may sound overly pedantic, but Java code running in an applet in the browser has exactly the same "same origin" restriction as JavaScript on the browser, while Java on a server, or even JavaScript *on a server*, is unrestricted.)
Laurence Gonsalves
A: 

$("#divId").load("documentname.html");

Yashwant Chavan