2013-04-09 51 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回调函数读取它,并按照您的需要进行操作。