开发者

How to dynamically add an option to a select list that is build using json data retrieved from a php script?

开发者 https://www.devze.com 2023-01-21 16:18 出处:网络
I have an HTML form that builds a drop-down from json data that is retrieved dynamically on page load from a php script.

I have an HTML form that builds a drop-down from json data that is retrieved dynamically on page load from a php script.

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascri开发者_Python百科pt">
$(document).ready(function() { 
        jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
        $.each(jsonData, function (i, j) {
        document.index.user_spec.options[i] = new Option(j.options);
     });});
     });
</script></head>
<body>
<form name="index">
<select name="user_spec" id="user_spec" />
</form>
</body>
</html> 

The php script fetches data from a MySQL table.

<?php  
      $username = "user";  
      $password = "********";  
      $hostname = "localhost";  
      $dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect   
      to MySQL");  
      $selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");  $query =
      "SELECT * FROM user_spec";  
      $result=mysql_query($query);     
      $outArray = array(); 
      if ($result) { 
      while ($row = mysql_fetch_assoc($result)) $outArray[] = $row; 
    } 
      echo json_encode($outArray);  
?> 

I need to add functionality to it now that new options can be added dynamically from the form to the list. How can I do it? I am thinking to do it like user adds an option to a text box & presses a button. The same JSON data is modified & posted back to server that reads & stores it into database. The list is refreshed/re-drawn with this changed data.


 jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {

    $("#user_spec").html("");//clear old options
                jsonData= eval(jsonData);//get json array

                for (i = 0; i < jsonData.length; i++)//iterate over all options
                {
                  for ( key in jsonData[i] )//get key => value
                  { 
                        $("#user_spec").get(0).add(new Option(jsonData[i][key],[key]), document.all ? i : null);
                  }
                }

 });
0

精彩评论

暂无评论...
验证码 换一张
取 消