我的javascript函数不会重定向到其他页面

时间:2013-06-12 23:12:07

标签: php javascript xmlhttprequest

我首先有两个项目是一个下拉框,一旦用户选择其选项将触发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();

            }

1 个答案:

答案 0 :(得分:2)

您的表单已提交,即浏览器会将数据发布到找到您网页的同一位置。你好像不想那样。因此,您应该阻止提交表单。要实现这一点,您不应该听取按钮的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;
    }