1

我知道这类问题在这里经常出现。我通常不是问问题的类型,但这次我无法通过搜索找到解决方案。

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

我有 3 个文件:

索引.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>

内容.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.php 有一个复选框和一个文本字段。当复选框被选中和取消选中时,它会执行一个 javascript 函数,将选中/取消选中放在文本字段中。很简单,一切正常。现在我想做的是在 content.php 加载的那一刻调用函数 checkbox() 。在此示例中,这意味着文本框已经具有“未选中”值,而不仅仅是在复选框被选中并再次取消选中之后。

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

不知何故,我觉得必须有一个简单的解决方案。我对javascript还是很陌生,所以我还不知道进出。

任何帮助将不胜感激

非常感谢!

4

2 回答 2

2

试试这个

   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
        document.getElementById(divcontainer).innerHTML=xmlhttp.responseText;
        checkbox();
   }
于 2013-10-31T08:41:35.140 回答
0

如果你是 JS 新手,你绝对应该看看 jQuery。使 AJAX 更简单。

$.ajax({
    url: youURL, 
    success: function (){
        //or whatever function you want to be called after success :)
    }
});
于 2013-10-31T08:45:25.957 回答