2013-06-12 57 views
0

我有兩個項目首先是一個dropdownbox,一旦用戶選擇它的選項會觸發一個javascript代碼,並顯示在同一頁面上的結果,我的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(); 

      } 
+0

這看起來有用 - 頂一下答案http://stackoverflow.com/questions/4048406/javascript-select-drop-down-menu-onchange-not-firing-properly即發送的選擇本身並使用'var criteria1 = crit1.options [crit1.selectedIndex] .value;'(使用正確的變量名稱)在JavaScript中獲得選項。 –

回答

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; 
    } 
相關問題