Javascript 如何将所选下拉项保存到数据库表
我有一个dropdownlist,我从数据库中获取,并在php文件中显示,如下所示:Javascript 如何将所选下拉项保存到数据库表,javascript,php,ajax,Javascript,Php,Ajax,我有一个dropdownlist,我从数据库中获取,并在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/banan
<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将其保存到不同的表中?
也欢迎使用Ajax解决方案。您需要的是:
在选择选项更改时,是否更新表?
试试这个
<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>
我没有在下拉列表中使用php文件。我正在访问json文件并创建下拉数组。json文件已经使用php文件创建。因此不确定/myphpfile.php将如何应用。请注意,在Ajax请求之前,我做了一个说明,解释了为什么-最好将数据添加到像mySQL这样的数据库中,然后从那里生成JSON文件。但是,您可以按照自己的意愿发送此信息。通过这种方式,您可以将数据从那里发送到JSON文件,而不是像您所希望的那样: