如何通过Ajax发送HTML和Javascript [英] How to send both HTML and Javascript through Ajax
问题描述
我想使用AJAX调用从同一页面检索HTML和Javascript.但是,我不确定执行此操作的最佳,最清洁和最安全的方法是什么.我希望我的Javascript在客户端上编辑一个已定义的对象.到目前为止,我的想法是:
I want to retrieve HTML and Javascript from the same page using AJAX calls. However, I'm not sure what the best, cleanest, and safest way to do this is. I want my Javascript to edit an already defined object on the client. So far, my idea is:
在某些事件上执行的客户端脚本:
Client-side script executed on some event:
getMoreStuff = function () {
$.ajax({
url: '/someRoute',
success: function (data) {
$data = $(data);
$things = $data.find('#things');
$('#content').append($things);
// Execute the script
}
})
}
AJAX请求的正文:
Body of AJAX request:
<div id="things">
<div class="post">...</div>
<div class="post">...</div>
<div class="post">...</div>
<div class="post">...</div>
<div class="post">...</div>
</div>
<script>
(function() {
window.things || (window.things = []);
things.concat([...some array...]);
})();
</script>
我不确定在定义$data
时我的jQuery代码是否执行它.还是应该将脚本作为字符串发送并使用eval?
I'm not sure if my jQuery code executes it when I define $data
. Or should I send the script as a string and use eval?
这项工作可以吗?
$(document.body).append($data.find('script'));
推荐答案
请参见dataType 此处
See dataType here
"html":以纯文本形式返回HTML;评估包含的脚本标签 当插入DOM时.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
这篇关于如何通过Ajax发送HTML和Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!