Search code examples
jqueryhtmlajaxcross-domainjsonp

Displaying a particular div from jsonp returned with whateverorigin.org dynamically


I need to get the whois information about certain sites and display it onto my website. I managed to implement it, but its not a straight forward method, and i think its possible to do this in a better way. This is how i did it

for eg i needed the whois info of http://megaanswers.com/ so with whateverorigin.org i got the jsonp request as below http://whateverorigin.org/get?url=http%3A%2F%2Fwww.domaininformation.de%2Fwhois%2Fmegaanswers.com (after encodeURIComponent) but this contains the whole page, but i just needed the part of the page within class="result" .

Now data.contents would give the html code of the whole page. And this html code is appended to the div with id="target" using jquery and the the div is given style="display:none;", so that the div is not displayed on the page. Now the element with class result is selected using jquery and its html is appended to the div with id="realtarget"

This is how the final code would look like

<div id="target" style="display:none;"></div>
<div id="realtarget"></div> 
<script>            
                $.ajaxSetup({
    scriptCharset: "utf-8", //maybe "ISO-8859-1"
    contentType: "application/json; charset=utf-8"});

    $.getJSON('http://whateverorigin.org/get?url=' + 
    encodeURIComponent('http://www.domaininformation.de/whois/megaanswers.com') + '&callback=?',
    function(data) {

        var thecontents = data.contents;
        $('#target').html(thecontents);

        var required = $('.result').html();
        $('#realtarget').html("<pre>" + required + "</pre>");

});

</script>

But is it possible to do this without first appending the html code of the whole page to the div with id="target" and then selecting the required class="result"(directly selecting the class="result"). Any help is appreciated


Solution

  • with jquery you can select elements into a variable. (but not to edit it in): try this:

    function(data) {
         var thecontents = data.contents;
         var required = $('.result', thecontents).html(); // select '.result' class in 'thecontents'
         $('#realtarget').html("<pre>" + required + "</pre>");
    });
    

    demo: http://jsfiddle.net/f97WG/2/