2017-03-02 116 views
0

我有我可是從我的數據庫中獲取並在我的PHP文件顯示下拉列表如下:如何保存選擇下拉列表項的數據庫表

<script type="text/JavaScript"> 
//get a reference to the select element 
var $select = $('#bananas'); 

//request the JSON data and parse into the select element 
$.getJSON('http://127.0.0.1/folder/bananas.json', function(data){ 

    //clear the current content of the select 
    $select.html(''); 

    //iterate over the data and append a select option 
    $.each(data.allbananas, function(key, val){ 
    $select.append('<option id="' + val.id + '">' + val.name + '</option>'); 
    }) 
}); 

我的html文件

<select id="bananas" class="form-control"> 
<option value="">-- Select A Banana -- </option></select> 

但我需要用戶從表單中選擇每個香蕉,當他或她提交時,必須使用php將其保存到不同的表格中。如何查看下拉列表是否來自json文件? 也歡迎Ajax解決方案。

回答

1

你需要的是: 選擇選項更改,更新表?我沒有使用下拉list.I一個php文件 試試這個..

<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </head> 
    <body> 
     <select id="bananas"> 
      <option value="1">Option 1</option> 
      <option value="2">Option 2</option> 
      <option value="3">Option 3</option> 
     </select> 
    </body> 
</html> 

<script> 
     $("#bananas").change(function(){ 
      // var option holds the selected option value whenever changed 
     var option = $("#bananas").val(); 
     console.log(option); 

      /* 
      It would be better practice to add the data to a DB like mySQL and then generating a JSON file from there 
      However you can just send this information as you already wanted this way 
      */ 
      $.ajax({ 
       url: './myphpfile.php', 
       data: 
       { 
        option:option 
       } 
      }).done(function(resp){ 
       if(resp == 200) { 
        console.log("Success!"); 
       }else if(resp == 0){ 
        console.log("Failed.."); 
       } 
      }); 
     }); 
</script> 
+0

正在訪問一個JSON文件和創建下拉array.The JSON文件中使用PHP file.Hence不知道如何已經創建/ myphpfile.php將適用。請詳細說明 –

+0

我在Ajax請求之前做了一個說明,解釋了爲什麼 - 「將數據添加到像mySQL這樣的數據庫然後從那裏生成JSON文件是更好的做法 但是,您可以按照您以前所希望的方式發送此信息「您可以將數據從此處發送到JSON文件,而不像您喜歡的那樣發送:) – user7071381

相關問題