简体   繁体   中英

Get objects from javascript using URL without loading the document

I have an URL which links to a HTML docment, and i want to get objects of the document without load the URL in my browser. for instance, i have an URL named: http://www.example.com/ , how can i get one object (ie, by getElementsbyTagName) of this document?

Using Ajax calls, I guess.

This is long to explain if you have never used XHR, so here's a link: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Another option is to construct an iframe using

var iframe = document.create('iframe');
iframe.src = 'http://...';

You can't. You can omit, at best, extraneous files being linked to from within the document like javascript or css, but you can't just grab one part of the document.

Once you have the document, you can grab out of it a section, but you can't just grab a section without getting the whole thing first.

It's the equivalent of saying that you want the 2nd paragraph of an essay. Without the essay, you don't know what the 2nd paragraph is, where it starts or ends.

Is this document in the same domain, or a different domain as the security domain your javascript is running in.

If it's in the same domain, you have a couple options to explore.

You could load the page using an XMLHttpRequest, or JQuery.get , and parse the data you're looking for out of the HTML with an ugly regular expression.

Or, if you're feeling really clever, you can load the target document into a jsdom object, jQuerify it, and then use the resulting jquery object to access the date you're looking for with a simple selector.

If the url is on the same domain you can use .load() for example:

$("some_element").load("url element_to_get")

See my example - http://jsfiddle.net/ajthomascouk/4BtLv/

On this example it gets the H1 from this page - http://jsfiddle.net/ajthomascouk/xJdFe

Its hard to show using jsfiddle, but I hope you get the gist of it?

Read more about .load() here - http://api.jquery.com/load/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM