jQuery:评估ajax响应中的脚本

bob*_*obo 5 javascript xml jquery json

来自我的webapp的XML响应都有要添加到页面的HTML,有些还有要运行的脚本.

我正试图从我的webapp发回XML,如:

<?xml version="1.0"?>
<doc>
  <html-to-insert>
    <![CDATA[<p>add me to the page</p>]]>
  </html-to-insert>
  <script>
    <![CDATA[ alert('execute me'); ]]>
  </script>
</doc>
Run Code Online (Sandbox Code Playgroud)

我现在正在做的是抢购<html-to-insert><script>CDATA,将html插入页面并进行评估<script>.

我正在寻找对我的方法的批评.任何人的建议?

Cri*_*oma 8

您可以使用jQuery库向后端发出XML请求并解析它

$(document).ready(function()
{
  $.ajax({
    type: "GET",
    url: "your/url/that/returns/xml",
    dataType: "xml",
    success: function (xml) {
      // xml contains the returned xml from the backend

      $("body").append($(xml).find("html-to-insert").eq(0));
      eval($(xml).find("script").text());
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里这里找到更多关于jQuery的信息

我没有测试它,但它应该根据这篇文章工作.


St.*_*and 3

您宁愿发送 JSON,它更容易解释。例子:

// Suppose your response is a string:
// { html: "<p>add me to the page</p>, script:"alert('execute me');" }
var obj = eval( "(" + response + ")" ) ;
eval( obj.script ) ;
Run Code Online (Sandbox Code Playgroud)