从表单调用同一页面内的JS函数(AJAX)


Calling JS function(AJAX) within the same page from a form

我试图在用户输入文本并按下提交按钮后在同一页面中执行AJAX函数脚本。

提交后,AJAX脚本将把结果发送给findme.php,后者对数据库执行查询。在实现ajax函数之前,我已经对findme.php的查询进行了测试。

我采用了W3school的方法,但是没有。我无法调用脚本并将值发送到findme.php

有谁知道我做错了什么吗?

qwerty.php

<script>
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","findme.php?q="+str,true);
  xmlhttp.send();
}
</script>
 <tr>
<form name="search" method="post" action="">
Name: <input type="text" name="findName"/>
Location: <input type="text" name="findLocation"/>
Price: <input type="text" name="findPrice"/>
<Select NAME="123">
<Option type="checkbox" value="">
<Option type="checkbox" value="=">Equal
<Option type="checkbox" value="<">Less than
<Option type="checkbox" value=">">More than
</select>
<input onclick="showUser(); return false;" type="submit" name="search" value="Search"/>
</form>
  </tr>
<tr>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</tr>

调用函数后必须返回false,否则表单正在提交,导致ajax调用失败。

<input onclick="showUser(); return false;" type="submit" name="search" value="Search"/>

既然你使用的是input type =" submit",那就在表单上尝试onSubmit事件。asa

<form name="search" method="post" action="" onSubmit="return showUser();">

不要忘记return关键字。在showUser()中返回false;当str=="之类的