2013-04-09 56 views
0

我有一個使用onChange事件觸發mysqli查詢的下拉菜單。 查詢使用返回結果填充數組,該結果又被分配給$ _SESSION變量。

我試圖使用存儲在$ _SESSION變量中的數組來填充選擇框,只要下拉菜單中的值發生更改。

這是相關的JavaScript代碼:

xmlhttp.open("POST", "getStudentList.php?q="+yearGroup, true); 
xmlhttp.send(); 


var newStudentList =<?php echo json_encode($_SESSION['studentList']) ?>; 

    // clear select box 
    $('#studentList').empty();   

    // populate select box with JS array items 
    $.each(newStudentList, function(key, value) { 
     $('#studentList') 
       .append($('<option>', { value : key }) 
       .text(value)); 
    });      

    $('#studentList').selectmenu("refresh",true); 

$ _SESSION [「studentList」]正在以「getStudentList.php」正確更新,但更新不反映在內部調用JavaScript直到頁面重新加載...我如何使更新自動發生?

我檢查過去的帖子,但沒有發現任何真正有幫助或我明白的東西!我會很感激任何幫助 - 我是一個完全新手在使用JavaScript/JQuery的,並從一個地方拼湊了一堆PHP,所以請在我身上輕鬆一下。 (是的,我正在使用session_start()!)

預先感謝您!生成HTML頁面的源代碼時

回答

1

你可以做這樣的事情,

$("#studentList").on('change',function() { 
    $.ajax({ 
     url: "getStudentList.php", 
     dataType: "json", 
     success: function(newStudentList) { 

      // clear select box 
      $('#studentList').empty();   

      // populate select box with JS array items 
      $.each(newStudentList, function(key, value) { 
       $('#studentList').append($('<option>', { value : key }).text(value)); 
      }); 

      $('#studentList').selectmenu("refresh",true); 

     } 
    }); 
}); 
0

PHP代碼只運行。一旦瀏覽器運行JS代碼,PHP已經運行,並且你的文字產生了​​一串字符,就像你手動輸入了一樣。

爲了運行更多PHP代碼,您需要從服務器獲取新文件。這是AJAX背後的基本概念:你編寫一個JS函數,要求服務器尋找一個新的頁面,通常包含XML或JSON,但除此之外就像任何網頁一樣。不過,並不是顯示新的頁面,而是一個JS回調函數讀取它,並按照您的需要進行操作。