Friday, September 28, 2012

Jquery cross domain AJAX requests and HTML parsing list of image src using JQUERY MAP

Recently I have been working with Wikipedia, Wikimedia and had to do AJAX requests and parsing the returned HTML.

Javascript and JQUERY have problems when you try an AJAX query to cross-domain sites. I read the following article by Micahs

Making Cross Domain jQuery AJAX Calls and followed the method suggested using YQL and seems to work fine. I have repeated below the code mentioned in the article for reference.

//feel free to add querystring vars to this
var myurl="";
//make the call to YQL
//this data.results[0] is the return object you work with,
//if you actually want to do something with the returned json
} else {
var errormsg = '
Error: could not load the page.
//output to firebug's console
//use alert() for other browsers/setups

I have given below an example of parsing all the image source in a list of images.

The list item code snippet is given below

    <div class="thumb" style="width: 150px;"><div style="margin:15px auto;"><a href="//" class="image"><img alt="Adrien Ysenbrandt - Virgin and Child with Two Angels in a Landscape - Walters 37266.jpg" src="//" width="102" height="120" /></a></div></div>

After alert(data.results[0]); you can do something like the following to get the  thumb html in the list:

 var thumb_array_img = $(('.thumb img'), result);

To get all the src links in an array use the JQUERY map function like the following code:

image_thumb_array = [];

image_thumb_array = $(thumb_array_img).map(function ()

                   { return $(this).attr("src"); });

1 comment:

  1. Thanks ! for sharing this wonderful news with us.I really like your post as it is informative as well as interesting.I am also quite interested to see your upcoming post for Web Development so please keep writing.