如何通过 Ajax 发送 HTML 和 Javascript

How to send both HTML and Javascript through Ajax

本文关键字:Javascript HTML 发送 何通过 Ajax      更新时间:2023-09-26

我想使用 AJAX 调用从同一页面检索 HTML 和 Javascript。但是,我不确定最好,最干净,最安全的方法是什么。我希望我的Javascript在客户端上编辑已经定义的对象。到目前为止,我的想法是:

在某些事件上执行的客户端脚本:

getMoreStuff = function () {
  $.ajax({
    url: '/someRoute',
    success: function (data) {
      $data = $(data);
      $things = $data.find('#things');
      $('#content').append($things);
      // Execute the script
    }
  })
}

AJAX 请求的正文:

<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>

我不确定我的jQuery代码在定义$data时是否执行它。还是我应该将脚本作为字符串发送并使用 eval?

这行得通吗?

$(document.body).append($data.find('script'));

在此处查看数据类型

"html":以纯文本形式返回 HTML;计算包含的脚本标记 插入 DOM 时。