繁体   English   中英

PHP / ajax:表单获取方法不起作用

[英]php/ajax: form get method not working

我有两个php文件,test.php和test2.php
在“ test.php”中,我有一个表单,我想获取名称并用ajax和php回应它,这是我的代码,这是怎么了?

test.php

<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test2.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form method="get">
First name: <input type="text" name="fname">
<input type="submit" value="click me" onclick="showHint(fname)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>

test2.php

<?php
$q = intval($_GET['q']);
echo $q;
?>

表单中的按钮是提交输入,将导致页面重新加载。 向您的onclick方法添加return false可以防止这种情况的发生:

<input type="submit" value="click me" onclick="showHint(fname); return false">

此外,您的showHint函数需要一个字符串,但是您正在传递HTML输入。 您可以通过在函数顶部添加以下内容来获取文本值:

if (typeof str !== 'string' && typeof str.value !== 'undefined') {
    str = str.value;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM