2012-05-24 22 views
2

當上提交按鈕,Ajax的工作原理,並呼籲PHP頁面(不刷新)點擊,但是當按下輸入該refreshs頁面和腳本無法正常工作,只有?txtname=(INPUTED TEXT)出現在頁面網址的結尾。不同的行爲,並輸入

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> 
+0

請停止安裝活動在HTML標籤通過屬性。 –

+1

它看起來像表單正在提交輸入新聞。這不應該發生,因爲您的輸入類型是按鈕而不是提交。嘗試把表單的返回false onSubmit方法。 –

+0

您是否知道'XMLHTTP =新的ActiveXObject(「MSXML2.XMLHTTP」)//舊微軟Browsers'指的是IE5和IE5.5 .. EMM ..你確定這是你的初衷,或者只是一個不好的情況下複製粘貼? –

回答

3

您需要onsumbit屬性添加到您的窗體:

<form name="myForm" onsubmit="ajaxFunction(); return false;"> 

return false;是爲了防止頁面刷新(即實際提交而不是ajax)。

+0

它的工作,謝謝! –

2

應用處理程序提交表單的,不是點擊一個按鈕

<form name="myForm" onsubmit="ajaxFunction();"> 

這樣,你的函數將在任何情況下工作,是通過輸入或點擊按鈕提交的表單。

1

更換

<form name="myForm"> 

<form name="myForm" onsubmit="ajaxFunction();return false;"> 

因爲形式將與GET方法提交自己的頁面本身ENTER上,除非你定義什麼了ENTER按鍵做。

相關問題