how to load the Jquery response(HTML page with scr

2019-03-05 04:39发布

问题:

test1.html file:

<html>
<head>
<script src="jquery-1.7.2.js">
</script>
<script>

function loadfn(){

$.get('test.html',function(data){

alert($(data).text());
//$('body div#returnData').html(data);
$.each(data, function(i, node) { 
    alert(i);
   if (node.tagName == "SCRIPT") {
       eval(node.innerHTML); 

   } else {
       $(node).appendTo($('#returnData')); 
   }

});

});
test1();
test2();
}
</script>
</head>
<body>
<div id="returnData" >
</div>
<input type="button" value="Click" onclick=loadfn()>
</body>
</html>

test.html :

<html>
<head>
<script src="/jquery-ui-timepicker-addon.js">
</script>
</head>
<script>
function test1(){
alert('test1 function');
}
</script>
<script>
function test2(){
alert('test2 function');
}
</script>
<body>
<div id="testdiv">
Text field : <input type="text" value="Test Value"/>
</div>
</body>
</html>

Actually i have the requirement that i have to load the test.html page into test1.html and then run the script functions that are there in that page.

The Above code snippet doesnt suffice the requirement. Please let me know what i am doing wrong in the code snippet.

回答1:

you need to do something like this so that it loads script element , so my advise is when you get response replace script string with scri" + "pt

var code = "<script>alert('Hi!');</scr"+"ipt>";
$('body').append($(code)[0]);


回答2:

You need not "load" it into your DOM. For script tags, you could just do..

eval("<script>alert('Hi!');</script>");

UPDATE :

If you result contains both HTML and SCRIPT nodes, do the following..

$.each(nodes, function(i, node) { //result might contain muliple HTML/Script nodes

   if (node.tagName == "SCRIPT") {
       eval(node.innerHTML); 
       //Appending to DOM also executes the script. So we do eval() instead, which does the equivalent.
   } else {
       $(node).appendTo($('#returnData')); //And append your HTML nodes to the desired target div
   }

});