Execute ajax to return the Javascript script in the HTML snippet

Source: Internet
Author: User
Tags javascript eval
ArticleDirectory
    • I. Problem Description
    • 2. Two solutions

If the data loaded by Ajax is an HTML clip that also contains a script <SCRIPT> block, you can use XMLHTTP to load the data. responsetext is inserted into an element of the current document using the innerhtml method. You will find that the script loaded by Ajax is not executed at all. This is a common problem in Ajax development. If you haven't been using JavaScript frameworks for development, I believe you have long known this problem. This article analyzes two solutions, one of which is to explain the implementation of the jquery framework.

I. Problem Description

The following is a simple example to illustrate the problem. In the following example, assume that the variable responsetext is the HTML fragment data loaded by Ajax. A message is displayed in the script, and the innerhtml method is used to insert the DIV whose ID is ajaxdata, you may expect to see the pop-up message box, and you will find no. The problem is like this.

< Div ID = "Ajaxdata" > </ Div >
< Script Type = "Text/JavaScript" >
VaR Responsetext =   ' <P> This is a paragraph </P> <SCRIPT> alert ("This is the script snippet loaded by Ajax") </SCRIPT> ' ;
Document. getelementbyid ( ' Ajaxdata ' ). Innerhtml = Responsetext;
</ Script > 2. Two solutions

1. Execute the script using Javascript eval method.

The specific implementation idea of this method is to put XMLHTTP. the scripts in responsetext are extracted. No matter how many script blocks are contained in the HTML loaded by Ajax, we can call the eval method to execute the scripts. The following provides an encapsulated function:

Function Executescript (HTML)
{
VaR Reg =   / <SCRIPT [^>] *> ([^ \ x00] +) $ / I;
// Split the entire HTML segment by <\/SCRIPT>
VaR Htmlblock = Html. Split ( " <\/SCRIPT> " );
For ( VaR I In Htmlblock)
{
VaR Blocks; // Blocks [1] is the real script content that matches the regular expression content array, because we used brackets to capture the previous Reg definition.
If (Blocks = Htmlblock [I]. Match (REG ))
{
// Clear comments that may exist. For the end of the comment --> you can ignore the processing, and the eval works normally.
VaR Code = Blocks [ 1 ]. Replace ( / <! -- / , '' );
Try  
{
Eval (CODE) // Execute scripts
}
Catch (E)
{
}
}
}
}

The usage of this method is as follows. Add the HTML Method to the DOM using the innerhtml method and call 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 an external script call like this:
<SCRIPT type = "text/JavaScript" src = "/JS/common. js"> </SCRIPT> the executescript method cannot execute this externally loaded script in depth.

2. Learn and use the implementation of the jquery framework

Jquery loads HTML for Ajax, and finally implements the entire XMLHTTP when the HTML (value) method is executed. responsetext converts data to Dom, uses dom-related operation methods to find the scripts, and inserts these scripts into the head. The specific principle is hard to say. Let's give a simple example and then analyze the general idea. First look at the example:

$. Get ( ' Ajax. aspx ' , Function (Data)
{
$ ( ' # Div1 ' Pai.html (data );
});

Now let's assume that the above Ajax. ASPX page returns an HTML clip that contains one or more script blocks or even external script references. Div1 is the ID of a div tag on the page where an Ajax request is initiated.CodeThe result is that the HTML in Ajax. aspx is loaded into a div tag with ID div1.

In the anonymous callback function, you can use typeof (data) to find whether data is the original string, which is equivalent to XMLHTTP. responsetext: It is found through code execution tracking that the execution and processing of script fragments loaded by Ajax is not in the code of jquery's Ajax module, but in the HTML (value) method, that is, when an HTML string containing a script block is inserted into the Dom, it is responsible for extracting the script for calling and processing. The HTML (value) method actually calls the append (value) method ......, The following methods are called throughout the process. arrows represent the order in which these methods are called:

HTML-> append-> dommanip-> clean-> evalscript-> globaleval

Among them, the clean method is particularly critical. This method is also an important method of jquery. It also involves fixing HTML errors (labels are not finished, table structure adjustment, and other methods) and processing scripts. Script extraction is also carried out here. See relatedSource code(Jquery1.3.2 ):

If (Fragment)
{
For ( VaR I =   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 , 0 ]. Concat (jquery. makearray (Ret [I]. getelementsbytagname ( " Script " ))));
Fragment. appendchild (Ret [I]);
}
}
Return Scripts;
}

In addition, the following code is also found in the evalscript method. Here we load the code in the same step like <SCRIPT type = "text/JavaScript" src = "/JS/Common. an external script such as JS "> </SCRIPT> solves a defect in the executescript method:

If (ELEM. SRC)
Jquery. Ajax (
{
URL: ELEM. SRC,
Async: False ,
Datatype: " Script "
});

At the same time, the following code is also found. delete the script in responsetext, because in this method, jquery is ready to put the extracted script into the head area, so deleting can avoid repeated script blocks in the final HTML:

If (ELEM. parentnode)
ELEM. parentnode. removechild (ELEM );

Finally, in the globaleval method, the head. removechild (SCRIPT); the method is to insert the script into the head and immediately remove the script tag. This also avoids repeated execution of the HTML (value) method to generate duplicate script blocks in the head area. This removal does not affect script execution, and does not clear the related variable values in the script block. Obviously, if you want to see the final execution result of HTML (data), such as the script block inserted to the head after extraction, You can temporarily comment out this line of code.

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.