2013-03-19 30 views
1

我正在使用javascript和php來獲取自動建議。將此值從Javascript傳遞到PHP文件

<div> 
     <div> 
      University Name:<input type="text" size="20" name="uni" value="" id="uniString" onkeyup="lookup(this.value);" onblur="fill();"> 
     </div> 

     <div class="suggestionsBox" id="suggestions" style="display: none;"> 
      <div class="suggestionList" id="autoSuggestionsList"> 
       &nbsp; 
      </div> 
     </div> 
    </div> 

當用戶輸入名稱時,我顯示結果並使用fill函數來獲取值。一切正常。但是,有什麼方法可以使用''thisValue''(這是選定的大學)打印下拉列表?我想打印選定的大學的課程,所以我寫了這個代碼:

function lookup(uniString) { 
    if (uniString.length == 0) { 
     // Make the suggestions box invisible 
     $('#suggestions').hide(); 
    } else { 
     $.post("autosuggestions.php", { 
      universityString: "" + uniString + "" 
     }, function(data) { 
      if (data.length > 0) { 
       $('#suggestions').show(); 
       $('#autoSuggestionsList').html(data); 
      } 
     }); 
    } 
} // lookup 

function fill(thisValue) { 
    if (thisValue) { 
     $('#uniString').val(thisValue); 
     var strURL = "findCourse.php?uniString=" + thisValue; 
     var req = getXMLHTTP(); 
     if (req) { 
      req.onreadystatechange = function() { 
       if (req.readyState == 4) { 
        // only if "OK" 
        if (req.status == 200) { 
         document.getElementById('coursediv').innerHTML = req.responseText; 
        } else { 
         alert("There was a problem while using XMLHTTP:\n" + req.statusText); 
        } 
       } 
      } 
      req.open("GET", strURL, true); 
      req.send(null); 
     } 
    } else { 
     setTimeout("$('#suggestions').hide();", 200); 
    } 
} 
findCourse.php: $uni = $_POST['uniString']; 
$query = mysql_query("SELECT .... FROM .... WHERE university.uni_name='$uniString' AND ......."); 
if ($query) { 
    .... 
}`enter code here` 

不幸的是,它不工作。我用'document.write()'測試了它..這個值打印出來並打印出大學的名字(這就是我想要的)。但是當我將值傳遞給php文件(getCourse.php)時,結果值爲null。

任何人都可以幫助我嗎?我很確定我的問題很愚蠢,對不起,我在JavaScript中並不擅長。

+2

你通過universityString而你的PHP腳本期待uniString。爲什麼? – 2013-03-19 16:57:07

+0

是的,我創建了2個PHP腳本。一個用於autosuggestions,一個用於下拉列表。第一個PHP腳本是期待universityString,第二個PHP腳本(findCourse.php)期望uniString :) – shieldcy 2013-03-19 17:11:44

回答

3
req.open("GET", strURL, true); 

$uni = $_POST['uniString']; 

如果您在ajax中使用get方法,則需要在PHP中使用$ _GET。

+0

這麼簡單大聲笑:P非常感謝你,我仍然有一些錯誤,但至少現在我有價值! – shieldcy 2013-03-19 17:10:27

0

在你的下面的代碼中,你應該用「uniString」替換「universityString」。

$.post("autosuggestions.php", {universityString: ""+uniString+""}, function(data){ 
    if(data.length >0) { 
    $('#suggestions').show(); 
    $('#autoSuggestionsList').html(data); 
    } 
}); 
+0

感謝您的回答。這是我在檢查自動瀏覽的PHP文件:)「universityString」是正確的。在這裏,我確實需要像你說的那樣使用「uniString」:var strURL =「findCourse.php?uniString =」+ thisValue; – shieldcy 2013-03-19 17:09:52

+0

好吧,這是因爲有2個PHP腳本。我剛剛看到你的評論。 – Pith 2013-03-19 17:36:29

0

使用jQuery .blur()

$('#uniString').blur(function() { 
    if ($('#uniString').val() =! '') 
    { 
     // DO POST 
    } 
}); 

如需更多幫助,請在功能查找學習.blur()