Run script tags loaded with ajax

戏子无情 提交于 2019-12-10 14:56:05

问题


General Question

Say you have a simple ajax request like $("#container").load('/url #content');. The loaded DOM will be something like

<a>email</a>
<script>/* some script */</script>

What can I do to get the contents of the script tags to execute?

Specific Question

Cloudflare automatically protects email addresses in the DOM by replacing the text with [email protected] and including a script that unravels it. However, the contents can be loaded asynchronously and the script that does the unraveling won't be executed. I could just turn off the email protection feature (I think) but I'm wondering if there's another way around this.

Example

See it in action at http://aysites.com/what -- click "Contact"


回答1:


There is a pure js function which invokes the JavaScript compiler. It's eval. You need to use it.

Examples:

jQuery.globalEval("var newVar = true;")

on jQuery.com

Or

eval("x=10;y=20;document.write(x*y)");
document.write("<br />" + eval("2+2"));
document.write("<br />" + eval(x+17));

on w3schools




回答2:


My answer includes some of Tooraj's magic as well.

Basically, we're going to use the same load function, and in the callback, we're going to grab the script, take the functions from within it, then eval them.

$("#container").load('/url #content', function(){
  eval($('#container script').html()); 
});

using the above selector and grabbing the HTML out of that selector (which happens to be the functions in the script), we can then eval that function and have it run.

Here's a working jsFiddle.




回答3:


you could put the script part alone in a page with appropriate headers and then use $.getScript() to get and execute the script,

See Doc: http://api.jquery.com/jQuery.getScript/



来源:https://stackoverflow.com/questions/11425718/run-script-tags-loaded-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!