jQuery未在Ajax请求的脚本标记中加载js文件 [英] jQuery is not loading js file in script tag of ajax request
问题描述
我有一个ajax POST请求,此请求带有带有引用外部js文件的带有<script src="">
标记的html,当我将此html插入DOM时未加载JS,我在做什么错了?我记得在加载外部script1和script2时没有问题.
I have an ajax POST request, this request comes with html with <script src="">
tags referencing external js files, when I insert this html in DOM the JS are not loaded, what I'm doing wrong? I can remember see this working loading the external script1 and script2 without problems.
请求:
$.ajax({
type: 'POST',
dataType: 'xml/html',
cache: false,
url: "/html/with/scripttags",
data: {somedata:'value'},
success: function(data) {
$('body').append(data)
}
});
已加载内容:
<link rel="stylesheet" media="all" href="http://domain.com/application.css" />
<script src='http://domain.com/script.js' type='text/javascript'></script>
<script src='http://domain.com/script2.js' type='text/javascript'></script>
<script type='text/javascript'>alert('executed')</script>
<div>BLAALBLABLAB</div>
但是,脚本标记中的警报执行没有问题,并且application.css
外部文件已加载而没有问题.看起来jQuery无法加载文件,我还检查了网络标签.
However the alert in script tag is is executed without problems and the application.css
external file is loaded without problems. Looks like jQuery doesn't load the files, I also check the network tab..
推荐答案
这是jQuery的正常行为,如果要包含脚本,则需要解析html并手动添加它们.
That's jQuery's normal behaviour, if you want to include your scripts, you need to parse the html and add them manually.
坏消息:您甚至无法使用$()
...选择字符串中的script
标签...
Bad news: you can't even select script
tags in strings with $()
...
我没有对此进行测试,但是这个快速而肮脏的示例应该可以工作:
I didn't test that, but this quick and dirty example should work:
function createGetScriptCallback(url) {
return function () {
return $.getScript(url);
}
}
$.ajax({
type: 'POST',
dataType: 'xml/html',
cache: false,
url: "/html/with/scripttags",
data: {
somedata: 'value'
},
success: function (data) {
var parser, doc, scriptsEl, callbacks;
parser = new DomParser();
doc = parser.parseFromString(data, "text/html")
scriptsEl = doc.querySelectorAll("script[src]");
callbacks = []
for (var i = 0; i < scriptsEl.length; i++) {
callbacks.push(createGetScriptCallback(scriptsEl[i].getAttribute("src")));
}
$.when.apply($, callbacks)
.fail(function (xhr, status, err) {
console.error(status, err);
});
$('body').append(data);
}
});
但是您不应该依赖html来加载脚本.
But you should not depend on the html to load your scripts.
编辑:更少的脏代码(受@ guest271314的回答启发)
edit: less dirty code (inspired by @guest271314 's answer)
这篇关于jQuery未在Ajax请求的脚本标记中加载js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!