开发者

AJAX - OnSubmit Problem

I am fairly new to AJAX so please forgive me.

I have to forms - the fist one works but the second does not and I don't know why. The fist html form does not have submit button but the second does. They both use the same javascript function.

<script type="text/javascript">
function showUser(str)
{
if (str=="")
 {
 document.getElementById("txtHint").innerHTML="";
 return;
 } 
if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
else
 {// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
   document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
   }
 }
xmlhttp.open("GET","server_script.php?q="+str,true);
xmlhttp.send();
}
</script>

From 1:

<form>
<select name="users" onchange="showUser(this.value)">
<option value="0001">0001</option>

0002

Person info will be listed here.

From 2:

<form onsubmit="showUser(this.foo.value)">
<input type="foo" >
<input type="submit" >
</form>
<br />
<div id="txtHint"><b>Person info will 开发者_StackOverflow中文版be listed here.</b></div>


On the first one your ajax is firing onchange, as such there is no default behaviour that is going to interfere with that.

On the second form you are using the onsubmit event, which has the default behaviour of posting back the form to the server. So you have to return false or preventdefault on that event to allow your ajax code to complete. The easiest fix would be to simply add a return false:

<form onsubmit="showUser(this.foo.value); return false;">


Make showUser return false, otherwise the form will be submitted by the browser by the usual means.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜