我正在構建在線計算器,並試圖通過AJAX發送值以通過php腳本處理它們。來自服務器的響應設置爲div,但該div在顯示後立即消失。我的Ajax代碼是:響應div在ajax請求後不斷消失
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // calls the function for the XMLHttpRequest instance
// gets data from form fields, using their ID
var c1 = document.getElementById('c1').value;
var c2 = document.getElementById('c2').value;
var c3 = document.getElementById('c3').value;
var c4 = document.getElementById('c4').value;
var c5 = document.getElementById('c5').value;
var c6 = document.getElementById('c6').value;
// create pairs index=value with data that must be sent to server
var the_data = 'c1='+c1+'&c2='+c2+'&c3='+c3+'&c4='+c4+'&c5='+c5+'&c6='+c6;
request.open("POST", php_file, true); // sets the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // sends the request
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById("ajaxform").submit();
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
請注意,我用的引導CSS框架的實際現場和響應DIV未施加任何類。
感謝
表單提交是否會導致回發,加載新頁面? – Musa 2013-04-30 20:28:09
很高興知道你得到的迴應是什麼,以及頁面中的一些html。 – 2013-04-30 20:28:28
有沒有想過看着'jQuery.ajax()'? – 2013-04-30 20:29:13