在单击提交按钮时将文本值传递给 AJAX 函数


passing text value to ajax function on clicking submit button

我有一个由文本字段组成的表单(id="txt1")和一个提交按钮(id="提交")。Ajax 函数 'showhint()' 在提交按钮的 'onclick' 事件上被调用。

<form action="">  
<input type="text" id="txt1"   />
<input type="submit" id="submit" onclick="showhint()"/>
</form>

和 ajax 函数

    function showhint(){
var xmlhttp;
if(window.XMLHttpRequest)
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmllhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("txthint").innerHTML=xmlhttp.responseText;
    }
        }
            xmlhttp.open("GET","gethint.php",true);
            xmlhttp.send();
            }

在这里 gethint.php 是 showhint() 函数完成其工作的页面,而编写 ajax 响应的目标div 是 "txthint" 。我想要的是将文本值(表单)传递给 ajax 函数。有什么简单的方法吗?等待响应,任何有用的响应都将是非常可观的。 阿达万斯的塔克斯

var value = document.getElementById("txt1").value;
xmlhttp.open("GET","gethint.php?value="+value,true);

在gethint中.php

 echo $_REQUEST['value'];

如果我没看错,您正在尝试获取文本框的值并将其传递给您的 showhint() 方法。

试试这个:

<input type="submit" id="submit" onclick="showhint(document.getElementById('txt1').value)" value="test"/>

然后你可以接受这样的值:

function showhint(value) {
  // use value here
}

希望有帮助。