我正在尝试使用 Flask 和 MySQL 设置一个小型 Web 应用程序,该应用程序从页面上的单选按钮获取信息并将其发送到数据库中。我对 webdev 很陌生,所以我仍然坚持从按钮中实际获取信息。
这是我的单选按钮的 HTML(去掉缩进):
<div>
<input id="radioB" type="radio" name="radios" value="b" checked="checked">
<label for="radioB"><span><span></span></span>B</label>
</div>
<div>
<input id="radioT" type="radio" name="radios" value="t">
<label for="radioT"><span><span></span></span>T</label>
</div>
这是我的脚本:
$(function(){
$('#btnSubmit').click(function(){
$.ajax({
url: '/submit',
data: $('radios:checked').val(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
在我的 flask 代码中,我尝试使用以下方式请求它:
_info = request.form['radios']
当我当前尝试运行此程序时,我得到一个
"POST /submit HTTP/1.1" 400 -
flask 日志中的错误,使我相信我的问题在于脚本的“数据”部分和/或 flask 请求。任何有关此部分的帮助将不胜感激!
编辑:我已将我的 html 更改为:
<form action ="/submit" form method="post">
<div>
<input id="radioB" type="radio" name="radios" value="b" checked="checked">
<label for="radioB"><span><span></span></span>B</label>
</div>
<div>
<input id="radioT" type="radio" name="radios" value="t">
<label for="radioT"><span><span></span></span>T</label>
</div>
<input type="submit" id="btnSubmit">
和我的 JS 脚本:
$(function(){
$('#btnSubmit').click(function(){
var radioValue = $("input[name=radios]:checked").val();
alert(radioValue);
$.ajax({
url: '/submit',
data: {value:radioValue},
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
现在我在浏览器控制台中得到了上述 JS 脚本的错误情况,而不是之前的错误。
最佳答案
尝试 $("input[name='radios']:checked").val();
获取单选按钮值,我希望你能得到解决方案
$(function(){
$('#btnSubmit').click(function(){
var radioValue = $("input[name=radios]:checked").val();
alert(radioValue);
$.ajax({
url: '/submit',
data: {value:radioValue},
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<div>
<input id="radioB" type="radio" name="radios" value="b" checked="checked">
<label for="radioB"><span><span></span></span>B</label>
</div>
<div>
<input id="radioT" type="radio" name="radios" value="t">
<label for="radioT"><span><span></span></span>T</label>
</div>
<input type="submit" id="btnSubmit">
</form>
关于javascript - 使用 javascript 从单选按钮获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42405963/