1

我有一个 ajax 调用,它返回以下响应:

<div class="content">
    <script language="JavaScript">  
        function validate(){
            alert('validate is working');
        }
    </script>
    <div class="container">
        <a href="#" onclick="javascript:validate();">my button</a>
    </div>
</div>

现在,我想将响应转换为 html 并将其附加到进行 ajax 调用的页面。

$.get('test.php', function(data) {
    $('#someTarget').append($(data).find('.content').html());
});

我已经尝试过上面的代码,但似乎这只是附加容器 div。有没有办法将 javascript 代码块附加到我现有的页面中?

4

1 回答 1

1

在您的代码中有两个问题:

$('#someTarget').append($(data).find('content').html());
  1. $(data)在将脚本插入 DOM 之前,会解析并执行脚本

  2. 假设你的意思$(data).find('.content').html()是 html() 返回内容的 innerHTML,你只需要$(data).

试试这个:

<div class="content">
    <style type="text/javascript">  
        function validate(){
            alert('validate is working');
        }
    </style>
    <div class="container">
        <a href="#" onclick="javascript:validate();">my button</a>
    </div>
</div>

现在有一个技巧:我<style>用来包装脚本,应该在解释并插入 DOM 之后执行。

$.get('test.php', function(data) {

    // parse HTML to DOM
    var $data = $(data);

    // take the scripts out
    var $inlineScripts = $('style[type="text/javascript"]', $data).remove();

    // Now append the DOM
    $('#someTarget').append($data);

    // And globalEval the scripts
    $inlineScripts.each(function () {
        $.globalEval(this.innerText);
    });
});

Okay for your simple validate function that gets called by a click handler, you currently don't need my trick for inline scripts, however you will need it, when you have active scripts, that should be executed after the HTML is parsed and inserted.

Update: If you don't want the '.content' to be inserted, don't use html() - because it returns a string, so you do parse the html twice. Use instead .append( $(".container", $(data)) ) or .append( $(data).find(".container") ).

于 2012-11-14T15:41:34.020 回答