通过ajax发布选定的选项 [英] Post a selected option via ajax
问题描述
假设我有一个带有 select
的 form
,如何通过ajax调用将所选的输入值发送到服务器?
Assuming I have a form
with a select
, how can I send the selected value of the input via an ajax call to my server?
$.ajax({
type: "POST",
url: "test2.php"
}).done(function(data) {
});
推荐答案
由于您已经在使用jQuery,一种简单的解决方案是使用其序列化功能.
Since you are already using jQuery, an easy solution would be to use its serialize function.
$.ajax({
type: "POST",
url: "test2.php",
data: $('select#meal').serialize()
}).done(function(data) {
});
此解决方案的优点是您不必担心编码或选择允许多个选择.
The nice thing about this solution is that you do not have to worry about encoding or the select allowing multiple selections.
请注意,我假定了一些类似这样的HTML:
Note that I assumed some HTML like this:
<select id="meal" name="meal">
<option>Option 1</option>
...
</select>
然后,在您的PHP脚本中,您可以简单地使用输入名称(在这种情况下为餐")作为 $ _ POST
数组中的键来访问该值:
Then, in your PHP script, you can simply access the value using the name of the input (in this case "meal") as the key in the $_POST
array:
$meal = $_POST['meal'];
这篇关于通过ajax发布选定的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!