为什么通过ajax加载后javascript不会工作?

时间:2014-03-14 20:38:24

标签: javascript jquery html ajax

我有一个包含此脚本的主页面,可将status.html加载到我的info-box_main div

window.onload = ajax_req('scripts/home/php/status.html', 'info-box_main');

加载的status.html文件如下所示。

<div id="status_update">
    <form id="status_form" method="post" action="/scripts/home/php/statusUpdate.php/">
        <textarea name="status_update" placeholder="Type Link update here. " id="status_field" ></textarea>
        <input type='submit' value='post'/>
    </form>
</div>

<div id='status-box'>
    <button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

    <script>
        function myFunction(name,job){
            alert("Welcome " + name + ", the " + job);
        }
    </script>
</div>

ajax_req函数

function ajax_req(file_location, document_element)
{
var xmlhttp;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }                                 //ajax update request
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(document_element).innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET",  file_location ,true);
xmlhttp.send();
}

除了javascript之外,一切正常。我收到一个错误,表示当我尝试单击按钮时未定义该功能。任何帮助都是极好的!这只是测试javascript ...而不是我需要的实际javascript

2 个答案:

答案 0 :(得分:2)

将元素的innerHTML属性设置为包含<script>标记的HTML内容字符串在我知道的任何浏览器中运行脚本内容。

如果你确实在使用jQuery,那么绝对没有理由编写自己的ajax工具,而jQuery .load()方法将为你处理脚本内容。

$('#info-box_main').load('scripts/home/php/status.html');

答案 1 :(得分:1)

如果将其包含在标题的脚本中,则此方法应该有效。

window.onload = function () {
    $('#info-box_main').load('scripts/home/php/status.html');
};

替代解决方案:

$(document).ready(function () {
    $('#info-box_main').load('scripts/home/php/status.html', function () {
        $("#status-box").bind("click", myFunction);
        // Seperate javascript from html, and only bind event once hmtl has loaded.
    });
};
function myFunction (name,job) {
    alert("Welcome " + name + ", the " + job);
}

如果您坚持内联您的javascript,我会考虑将脚本标记放在脚本标记中引用值的任何其他标记(例如示例中的按钮标记)之前。这样,您可以确保在引用其值之前已对您的脚本标记进行了评估。