我有两个项目,首先是一个下拉框,一旦用户选择其选项,就会触发 JavaScript 代码并在同一页面上显示结果,
第二个是输入框和搜索按钮,一旦用户输入内容并单击搜索按钮,它就会触发 javascript,但由于某些原因,它会将值添加到当前页面地址,而不是重定向到其他页面和 xmlhttp .status 返回 0。
它不是重定向到 class/myresults.php,而是将 item1 及其值添加到当前页面地址,即 www.myexample.com/index.php?item1=computer
我的表单不起作用
<form action="">
<input name="search" type="text" title="Search"/>
<input type="submit" value="search" onclick="finditem(this.form.search.value)"/>
</form>
function finditem(option){
alert(option); <<<<shows the correct entered value
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
alert(xmlhttp.status); << returns 0
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("Result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","class/myresults.php?item1="+option,true);
xmlhttp.send();
}
下拉框的java脚本有效
<select name="items" onchange="findbox(this.value)">
.....
</select>
function findbox(option){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("Result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","class/myresults.php?item2="+option,true);
xmlhttp.send();
}
最佳答案
您的表单被提交,即浏览器将数据发布到它找到您的页面的同一位置。你似乎不想要那样。因此,您应该阻止提交表格。为了实现这一点,您不应该监听按钮的 onclick
事件,而应该监听表单的 onsubmit
事件:
<form action="" onsubmit="return finditem(this.search.value)">
<input name="search" type="text" title="Search"/>
<input type="submit" value="search"/>
</form>
这是 JavaScript:(请注意,finditem
返回 false 以防止表单实际提交。)
function finditem(option){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("Result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","class/myresults.php?item1="+option,true);
xmlhttp.send();
return false;
}
关于php - 我的 javascript 函数没有重定向到其他页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076899/