Perform Ajax to return JavaScript scripts in HTML fragments

Source: Internet
Author: User
Tags script tag

If the Ajax-loaded data is an HTML fragment, and the HTML fragment contains scripts <script> blocks, then when you insert this data xmlhttp.responsetext into an element of the current document using the innerHTML method, you will The script that Ajax loaded back was found to be not executed at all. This is a common problem in AJAX development, and if you have not been developing with JavaScript frameworks, I believe you have discovered this problem already. This paper analyzes two solutions, one of which is to explain the implementation of the jquery framework.

First, the problem description

Here's a simple example to illustrate the problem. In the following example, assuming that the variable responsetext is the Ajax loaded HTML fragment data, which contains the script popup a message, using the innerHTML method to insert the DIV with the ID ajaxdata, you may expect to see the message box pop up, and you find no, That's the problem.

<DivId= "Ajaxdata"></div>
<script type = "Text/javascript" >var= ;
document.getElementById (ajaxdata). Innerhtml  responsetext;
</script> Ii. Two ways of solving

1. Use JavaScript's Eval method to execute the script.

The idea of this method is to extract the script from Xmlhttp.responsetext, regardless of how many script blocks the AJAX-loaded HTML contains, we call the Eval method to execute it on the script block we find. Here is a packed function:

functionExecutescript (HTML)
{
VarReg=/<script[^>]*> ([^\x00]+) $/I
//Press <\/script> split for entire HTML fragment
VarHtmlblock=Html.split ("<\/script>");
For(VarIInchHtmlblock)
{
VarBlocks//The content array that matches the regular expression, blocks[1] is the real script content, because the previous reg definition we used the parentheses to capture the grouping
If(Blocks=Htmlblock[i].match (REG))
{
//Clear possible comment markers, end-of-comment-can be ignored, eval works as expected
VarCode=blocks[1].replace (/<!--/,‘‘);
Try
{
Eval (code) // Execute script
            }
catch (E)
{
}
}
}
}

This method is used as follows to add HTML to the DOM using the innerHTML method, followed by calling the Executescript method to execute the script block:

document.getElementById ("div1"). InnerHTML = xmlhttp.responsetext;
Executescript (Xmlhttp.responsetext);

Obviously this method is still flawed if Xmlhttp.responsetext contains external script calls like this:
<script type= "Text/javascript" src= "/js/common.js" ></script>,executescript method can no longer execute this externally loaded script.

2. Learn and use the implementation of the jquery framework

jquery for Ajax loading HTML, is ultimately in the execution of the HTML (value) method when the entire Xmlhttp.responsetext data into the DOM, and then use the DOM related operations to find the script inside, and then insert these scripts into the head. The specific principle is not good to say, first give a simple example, and then analyze the general idea. First look at the example:

$.get ('ajax.aspx', function(data)
{
$ ('#div1'). HTML (data);
});

Now assume that the Ajax.aspx page above returns an HTML fragment and contains one or more script blocks, even external script references. DIV1 is the ID of a DIV tag on the AJAX Request Initiation page, and the result of the entire code implementation is that the HTML in the load ajax.aspx is populated with a DIV tag with an ID of DIV1.

In the anonymous callback function, you can find data or the original string through typeof (data). That is equivalent to Xmlhttp.responsetext, through code Execution trace discovery, the execution of the Ajax load script fragment is not in jquery's Ajax module code, but in the HTML (value) method, When inserting an HTML string containing a script block into the DOM, it is the responsibility of the extraction script to invoke processing. The HTML (value) method actually calls the append (value) method ..., the entire process probably calls the following methods, the arrows represent the order in which these methods are called:

Globaleval, Evalscript, Dommanip, append, html

The clean method is particularly critical, and this method is also an important method of jquery, which also involves fixing HTML errors (the way the tags are not finished, table structure adjustment, etc.) to process the script. The extraction of the script is also done here. Look at the relevant source code (JQUERY1.3.2):

If(fragment)
{
For(VarI=0; Ret[i]; I++)
{
If(Jquery.nodename (Ret[i),"Script")&&(!Ret[i].type||Ret[i].type.tolowercase ()==="Text/javascript"))
{
Scripts.push (Ret[i].parentnode?Ret[i].parentnode.removechild (Ret[i]): Ret[i]);
}
Else
{
If(Ret[i].nodetype=== 1                  ret.splice.apply (Ret, [i + 1, < Span style= "color: #000000;" >0].concat (Jquery.makearray (Ret[i].getelementsbytagname ( "script" ))));
            fragment.appendchild (Ret[i]);
        }
    }
    return scripts;
}

In addition, in the Evalscript method we also found the following code, here is the "same" step load like <script type= "Text/javascript" src= "/js/common.js" ></script> Such an external script solves a flaw in the Executescript method:

if (ELEM.SRC)
Jquery.ajax (
{
URL:ELEM.SRC,
Async: false,
DataType: "script"
});

Also found below code, this code is to delete the script in Xmlhttp.responsetext, because in this method, jquery is ready to put the extracted script into the head area, so delete can avoid the final HTML duplicate script block:

if (Elem.parentnode)
Elem.parentNode.removeChild (elem);

Finally, in the Globaleval method, we find Head.removechild (script) by inserting the script into the head and removing the script tag immediately, which is also to avoid the duplication of the HTML (value) method in the head area to generate duplicate script blocks. This removal does not affect the execution of the script, and the associated variable values in the script block are also not purged. Obviously, if you want to look at the final results of HTML (data) execution, such as what script blocks are inserted into the head after extraction, you can temporarily comment on this line of code first.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.