我正在通过在线教程学习 AJAX,并且正在尝试使用代码。
以下是教程中的代码:
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("POST", "serverTime.php", true);
ajaxRequest.send(null);
}
</script>
<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
<!-- ******* this is what I want to work with: ****--> <input type='text' name='time' />
</form>
</body>
</html>
我希望将结果打印到一个简单的<p>
标签而不是<input>
. 我尝试了以下方法,但没有奏效:
<p name="time"></p>
我究竟做错了什么?
编辑
根据以下答案,我将代码更改为:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var txtNode = document.createTextNode(ajaxRequest.responseText);
document.getElementById("time").appendChild(txtNode);
}
和
<p id="time"></p>
我仍然无法让它工作。我究竟做错了什么?