如何将选定的下拉项保存到数据库表

时间:2017-03-02 18:43:27

标签: javascript php ajax

我有一个下拉列表,我从我的数据库中取出并在我的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 个答案:

答案 0 :(得分:1)

您需要的是: 选择选项更改,更新表? 试试这个..

<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>