点击提交按钮时, ajax 工作, php 页面被调用( 没有刷新), 但按下键时, 刷新页面, 脚本不工作, 只有 < code>? txtname=( INPUTED TEXT) code > 出现在页面 URL 末尾 。
ajax 代码 :
var time_variable;
var root2 = location.protocol + // + location.host + /testing.php ;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}var root = location.protocol + // + location.host;
if (!xmlHttp && typeof XMLHttpRequest != undefined ) {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST",root2,true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader( Content-Type , application/x-www-form-urlencoded );
xmlhttp.send("txtname=" + txtname.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
html 部分 :
<body>
<form name="myForm">
<table>
<tr>
<td>Enter Name</td>
<td><input type="text" name="txtname" id="txtname" value="<?php echo $f ?>" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" value="Submit" onclick="ajaxFunction();" /></td>
</tr>
</table>
</form>
<div id="message" name="message"></div>
</body>