2013-10-31 85 views
1

我知道在这里弹出很多这类问题。我通常不是提问的类型,但是这次我无法通过搜索找到解决方案。AJAX加载后调用Javascript函数

我我的问题都归结到一个非常小的,简单的环境:

我有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加载的那一刻调用函数checkbox()。在这个例子中,这意味着文本框已经具有“未选中”的值,并且不仅在复选框被选中并且未被选中之后。

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

不知怎的,我觉得必须有一个简单的解决方案。尽管如此,我仍然对JavaScript非常陌生,但我还不清楚这些内容。

任何帮助将不胜感激

非常感谢!

+1

为什么你不使用类似jQuery的库来执行Ajax请求? – TiMESPLiNTER

+0

没有特别的理由。当我开始时,这是我发现对我有用的解决方案,从此我一直坚持。现在试试吧:) –

+0

有了一个JS库,你将拥有一个(或多或少)roch实体跨浏览器解决方案。所以我建议你使用一个lib。它也减少了要写入的代码量。 – TiMESPLiNTER

回答

2

试试这个

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

这就像一个魅力! 现在我想知道 - 是否还有一些方法可以通过content.php执行函数?我问,因为我有一个脚本,需要这一点。 –

0

如果you're新JS你一定要看看jQuery的。使AJAX变得更简单。

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