响应div在ajax请求后不断消失

时间:2013-04-30 20:24:52

标签: javascript ajax

我正在构建一个在线计算器并试图通过AJAX发送值来通过php脚本处理它们。服务器的响应设置为div,但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;


    }
  }
}

请注意,我正在为实际网站使用bootstrap CSS框架,而不在响应div上应用任何类。

由于

1 个答案:

答案 0 :(得分:1)

在您的onreadystatechange处理程序中,您提交的表单会导致页面提交(因此要更改的页面)。

request.onreadystatechange = function () {
    if (request.readyState == 4) {
        document.getElementById("ajaxform").submit(); // <-- ?
        document.getElementById(tagID).innerHTML = request.responseText;
    }
}

您再次看到同一页面这一事实意味着ajaxform表单没有设置action