Roman
Roman

Reputation: 2079

Extract elements from html using javascript

Suppose I have a webpage on the web, this page has many elements with ids. How do I fetch these elements using javascript? I've used this chunk with jQuery:

    $.get(websiteUrl, {}, function(results){
    //alert(results); // will show the HTML from anotherPage.html
    console.log($(results).find("bookId").html()); // show "bookId" div in results
    });

But I get error:

 XMLHttpRequest cannot load; Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.

Actually, I'm trying to fetch some data from webpage in Phonegap app on Android. Any ideas how to do this?

Upvotes: 2

Views: 185

Answers (2)

robrich
robrich

Reputation: 13205

You can use jsonp to do cross-domain ajax calls, though you don't get error or timeout callbacks. jsonp is natively supported by jQuery. http://api.jquery.com/jQuery.ajax/ The theory is you add a script tag to the page with a carefully formed url which includes the name of a callback function. The server then processes the ajax "request", and returns the answer as a single parameter tp your callback function.

Upvotes: 1

Madara's Ghost
Madara's Ghost

Reputation: 175017

Most browsers adhere to a strict same-origin policy. Meaning you can't make Ajax requests to a different server. While you can bypass it, it's not practical to do with every client.

Your best bet would be to invoke a server-side script to fetch it for you, and return the results to JavaScript.

Upvotes: 1

Related Questions