简体   繁体   English

如何通过Ajax发送HTML和Javascript

[英]How to send both HTML and Javascript through Ajax

I want to retrieve HTML and Javascript from the same page using AJAX calls. 我想使用AJAX调用从同一页面检索HTML和Javascript。 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. 我希望我的Javascript编辑客户端上已定义的对象。 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
    }
  })
}

Body of AJAX request: 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>

I'm not sure if my jQuery code executes it when I define $data . 在定义$data时,我不确定我的jQuery代码是否执行它。 Or should I send the script as a string and use eval? 或者我应该将脚本作为字符串发送并使用eval?

Would this work? 这会有用吗?

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

See dataType here 在此处查看dataType

"html": Returns HTML as plain text; “html”:以纯文本形式返回HTML; included script tags are evaluated when inserted in the DOM. 包含的脚本标记在插入DOM时进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM