I want to read the external HTML file in jQuery.ajax() to retrieve the elements.

Asked 2 years ago, Updated 2 years ago, 81 views

I'd like to retrieve elements by loading an external HTML file in jQuery.ajax().
Even if you specify an id name or a class name in the find, filter function, it cannot be retrieved.What should I do?
By the way, I would like to get multiple elements with the same class name in an array.

$( document).ready(function(){
    $.ajax({
        url: 'http://yahoo.co.jp',
        type: 'GET',
        dataType: "html",
        success:function(res){
        vardata=$(res)[0].responseText;// string retrieved

        var content=$(res.responseText).find('id name').text();//Unable to retrieve
        console.log(content);  

        }
    });
});

javascript html jquery ajax

2022-09-30 16:39

2 Answers

I didn't try with jquery.xdomainajax.js+ sample code, but when I saw and copied Yahoo's source in my browser, I encountered an event that I couldn't get.

As for the cause, it seems that even if the returned response HTML is passed directly to the jQuery function like $(response HTML), it cannot be converted into a jQuery object correctly.The reason is probably the following statement in the first line of HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN "http://www.w3.org/TR/html4/loose.dtd">

This sentence seems to be bad because jQuery cannot parse xml.
I cut this line as a trial and it worked.

var$jq=$(Response HTML.replace('<!DOCTYPE[^>]+>', ''))
$jq.find('#dsearch').text()//=> "Dictionary"


2022-09-30 16:39

How about using .parseHTML() and .filter()?

$(function(){
            var str1 = '';
            str1+='<html>';
            str1+='<body>';
            str1+='<h1>test</h1>';
            str1+='<divid="hoge" style="background-color:chartreuse">this and that</div>';
            str1+='<div>hoge</div>';
            str1+='</body>';
            str1+='</html>';
            varjq_obj=$($.parseHTML(str1));
            $("#data").append(jq_obj.filter("#hoge"));
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body id="data">

</body>


2022-09-30 16:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.