Php ajax代码期间的Javascript使用
我在重复这个问题。为了简化情况,我在index.php文件中提供了这个脚本Php ajax代码期间的Javascript使用,php,javascript,ajax,Php,Javascript,Ajax,我在重复这个问题。为了简化情况,我在index.php文件中提供了这个脚本 <form name="f" action="index.php" method="post"> <input type="button" name="but" id="but" value="Retrieve"> <div id="div"></div> <input type="submit" name="ok"> </form
<form name="f" action="index.php" method="post">
<input type="button" name="but" id="but" value="Retrieve">
<div id="div"></div>
<input type="submit" name="ok">
</form>
<script type="text/javascript">
document.getElementById("but").onclick = function(){
var http = false;
if (window.XMLHttpRequest){
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHttp");
}
if (http){
http.open("POST","other.php",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(){
if (http.status==200 && http.readyState==4){
document.getElementById("div").innerHTML = http.responseText;
}
};
http.send(null);
}
};
document.getElementById("y").onclick = function(){
alert("okaaay");
};
</script>
document.getElementById(“but”).onclick=function(){
var-http=false;
if(window.XMLHttpRequest){
http=newXMLHttpRequest();
}否则{
http=新的ActiveXObject(“Microsoft.XMLHttp”);
}
如果(http){
http.open(“POST”,“other.php”,true);
http.setRequestHeader(“内容类型”、“应用程序/x-www-form-urlencoded”);
http.onreadystatechange=函数(){
if(http.status==200&&http.readyState==4){
document.getElementById(“div”).innerHTML=http.responseText;
}
};
http.send(空);
}
};
document.getElementById(“y”).onclick=function(){
警报(“奥凯”);
};
并使用下面的脚本创建other.php文件
<?php
echo "<input type='text' name='y' id='y'>";
?>
更改代码,以便在other.php返回响应后设置“y”onclick,如下所示:
http.onreadystatechange = function(){
if (http.status==200 && http.readyState==4){
document.getElementById("div").innerHTML = http.responseText;
document.getElementById("y").onclick = function(){
alert("okaaay");
};
}
};
否则,您将在一个尚不存在的元素上设置该事件处理程序:-)我认为您应该只返回一些信息:
$response = json_encode( array('type'=>'text','name'=>'y','id'=>'y') );
print $response;
然后,当您收到它时(类型为application/json),使用javascript创建一个类型为input
的新元素,然后使用您收到的json为它提供所需的属性。一旦它被创建并存储在变量中,就将该元素放在div中