提交带有ajax和js的表单

时间:2012-02-05 17:28:00

标签: javascript ajax

所以我试图用js“解析”表单对象并传递本应用于URL的内容并使用ajax提交表单。代码不起作用.A和B参数未成功传递给服务器和我在第一时的想法一样回应。

<html>
<head>
<script type="text/javascript">
function ajaxForm(form){
 form = document.getElementById(form);
 var elements = form.elements;
 var content="";
 var element;
 for(i=0;i<elements.length;i++){
  element = elements[i];
  if(element.type=="text"){
     content += encodeURIComponent(element.name)+"="+encodeURIComponent(element.value)+"&";
     }
  }
  ajaxSubmit(content);
 }
function ajaxSubmit(content){
    if(content.length==0){
    document.getElementById("txtinput").innerHTML="";
}
if(windows.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
}
else{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        document.getElementById("txtinput").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","process.php?"+content,true);
xmlhttp.send();
}
</script>
</head>

<body>
<form id="ajax_form">
 A:<input type="text" name="A" />
<br/>
 B:<input type="text" name="B" />
<input type="submit" onsubmit="ajaxForm('ajax_form')" />
</form>
<p>Elevator:<span id="txtinput" ></span><br/></p>
</body>
</html>

process.php:

<?php 
 $response = "This is simply an example for debugging purposes";
 echo $response;
?>

2 个答案:

答案 0 :(得分:0)

尝试将encodeURLComponent更改为ecodeURIComponent

答案 1 :(得分:0)

永远不会调用AjaxForm和AjaxSubmit,而是以正常方式提交表单。你需要像

这样的东西
<form id="ajax_form" onsubmit="ajaxForm('ajax_form');return false;">