Home  >  Article  >  Web Front-end  >  Using AJAX to return JavaScript scripts in HTML fragments_javascript tips

Using AJAX to return JavaScript scripts in HTML fragments_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:37:121183browse

This is a very common problem in AJAX development. If you have not been using JavaScript frameworks for development, I believe you have discovered this problem long ago. This article analyzes two solutions, one of which explains the implementation of the jQuery framework.

1. Problem description
The following is a simple example to demonstrate the problem. In the following example, assume that the variable responseText is the HTML fragment data loaded by AJAX, which contains a script to pop up a message. Use the innerHTML method to insert it into the DIV with the ID ajaxData. You may expect to see the message box pop up, but you find that it does not. That's the problem.

Copy code The code is as follows:

< /div>


2. Two solutions Method
1. Use JavaScript’s eval method to execute the script.

The specific implementation idea of ​​this method is to extract all the scripts in xmlHttp.responseText. No matter how many script blocks the HTML loaded by AJAX contains, we can call the eval method to execute the found script blocks. . An encapsulated function is provided below:
Copy code The code is as follows:

function executeScript(html )
{
var reg = /]*>([^x00] )$/i;
//Split the entire HTML fragment by Split
var htmlBlock = html.split("");
for (var i in htmlBlock)
{
var blocks; // Content array matching regular expression, blocks[1] is a real script content, because we used brackets to capture the previous reg definition
if (blocks = htmlBlock[i].match(reg))
{
//Clear Possible comment tags can be ignored at the end of the comment -->, and eval will still work normally
var code = blocks[1].replace(/