如何在加载后运行AJAX加载的页面脚本

时间:2014-12-04 20:54:22

标签: javascript php jquery html ajax

我有一个这样的页面,page1.php代码将加载ajax:

...
<div id="myContent" >
<!-- ajax content load here -->
</div>
...

我的ajax代码是:

 $.ajax({
        type: 'post',
        url: 'codes/page.php',
        async: false,
        data: formDatas
        , success: function (response) {
            document.getElementById('myContent').innerHTML = response; // response contains page1.php codes
            }
        }
    });

这些数据将从page1.php加载:

<script>
    alert("hello");
</script>

<div>
    ...
</div>

现在我的问题是,当我直接加载page1.php时,会发出“hello”警告。但是当我通过ajax加载这些内容时,脚本不起作用而且没有提醒任何内容

如何在 myContent div中加载数据后运行这些脚本。

谢谢大家

2 个答案:

答案 0 :(得分:2)

对于遵循HTML5规范的浏览器(即所有当前主流浏览器),script elements inserted using innerHTML do not execute when they are inserted

但是,如果您使用jQuery的.html()方法,您的脚本将会执行:

$.ajax({
    type: 'post',
    url: 'codes/page.php',
    data: formDatas, 
    success: function (response) {
        $('#myContent').html(response);
    }
});

工作fiddle here

答案 1 :(得分:1)

你在那里有一个额外的结束括号,可能会导致错误(在document.getElementById下面)。此外,由于您使用的是jQuery,因此最好使用jQuery选择器语法和html函数。

尝试使用此代替当前代码...

$.ajax({
    type: 'post',
    url: 'codes/page.php',
    async: false,
    data: formDatas,
    success: function (response) {
        $('#myContent').html(response); //response contains page1.php codes
    }
});