在AJAX加载后调用Javascript函数

时间:2013-10-31 08:38:36

标签: javascript php html ajax

我知道这些问题突然出现在这里。我通常不是提问的类型,但这次我找不到解决方案。

我把我的问题归结为一个非常小而简单的环境:

我有3个文件:

的index.php:

<html>
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="javascript.js"></script>
<head>
    <title>Test</title>
</head>
<body>
<div>
    <input type="button" value="Show" onclick="show('content','content.php');">
    <script type="javascript/text">
        show('content','content.php');
    </script>
    <br>
    <div id="content"></div>
</div>

content.php

<div>CONTENT</div>
<input type="checkbox" id="checkbox" onclick="checkbox();">
<input type="text" id="textfield">

和javascript.js

function show(divcontainer,file){
var xmlhttp;
if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();                     
    } 
    else {                                                  
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
                    document.getElementById(divcontainer).innerHTML=xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", file);                  
            xmlhttp.send();         
}
function checkbox(){
    if(document.getElementById('checkbox').checked){
        document.getElementById('textfield').value = "checked";
    }
    else{
        document.getElementById('textfield').value = "unchecked";
    }
}

当我按下index.php中的按钮时,它会通过ajax调用将文件content.php加载到div容器“content”中。文件content.php有一个复选框和一个文本字段。选中并取消选中该复选框后,它会执行一个javascript函数,该函数将已选中/未选中的项放入文本字​​段中。 很简单,一切正常。 现在我想要做的是在加载content.php的那一刻调用函数复选框()。在此示例中,这意味着文本框已经具有“未选中”的值,而不仅仅是在复选框被选中并再次取消选中后。

将javascript代码放入文件content.php中没有做任何事情。

不知何故,我觉得必须有一个简单的解决方案。我仍然是javascript的新手,但我还不知道进出。

非常感谢任何帮助

非常感谢!

2 个答案:

答案 0 :(得分:2)

试试这个

   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
        document.getElementById(divcontainer).innerHTML=xmlhttp.responseText;
        checkbox();
   }

答案 1 :(得分:0)

如果你是JS的新手,你一定要看看jQuery。使AJAX更简单。

$.ajax({
    url: youURL, 
    success: function (){
        //or whatever function you want to be called after success :)
    }
});