从JS提取到网址



但是我会对如何从js发送这个结果作为获取感兴趣

<form method="GET" action="order2.php">
<input type="checkbox" name="obj" price="5" value="1" >5
<input type="checkbox" name="obj" price="15" value="2">15
<input type="checkbox" name="obj" price="20" value="3">20
<input type="submit" value="send">
<div id="test"></div>
<script type="text/javascript">
$(":input").change(function() {
var values = $('input:checked').map(function () {
return $(this).attr('price');;
}).get();
var total = 0;
$.each(values,function() {
total += parseFloat(this);
});
$("#test").text(total);
});
</script>
</form>

当我选择输入 1 和 2 以便结果在 url order2.php?price=20

$(":input").change(function() {
var values = $('input:checked').map(function () {
return $(this).attr('price');;
}).get();

var total = 0;
$.each(values,function() {
total += parseFloat(this);
});


$("#test").text(total);
$('form').attr('action', 'order2.php?price=' + total);
console.log ( $('form').attr('action') ) ;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
But I would be interested in how I can send this result from the js as a get
When I select inputs 1 and 2 so that the result is in url order2.php?price=20
<form method="GET" action="order2.php">
<input type="checkbox" name="obj" price="5" value="1" >5
<input type="checkbox" name="obj" price="15" value="2">15
<input type="checkbox" name="obj" price="20" value="3">20
<input type="submit" value="send">
<div id="test"></div>
</form>

从您的描述来看,当您选择选项 1 和 2 时,您将选项的总和作为价格。我将把它分解为几个步骤:

  1. 您必须对所选选项求和

  2. 构造查询参数

  3. 使用 Ajax 发出获取请求

这指导如何为发布和获取做Ajax教程。 希望这有帮助...

当表单提交时,它会将其所有输入附加到查询字符串或发布数据(取决于请求类型(。添加另一个名为price的字段参数的一种非常简单的方法是添加一个隐藏的输入并使用总和动态更新该输入。

请注意,我从复选框中删除了name属性。我这样做是为了他们不会被发送到表单提交中。

我还用 reduce(( 替换了您的forEach,因为它功能更强大,您可以将其与 map(( 链接

$("#myform input").change(function() {
var total = $('input:checked').map(function () {
return $(this).attr('price');
}).get().reduce(function(sum, value) {
return sum + parseFloat(value);
}, 0);
$(".price").val(total);
$(".price").html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="order2.php">
<input type="checkbox" price="5" value="1" >5
<input type="checkbox" price="15" value="2">15
<input type="checkbox" price="20" value="3">20
<input type="hidden" name="price" class="price"/>
<input type="submit" value="send">
</form>
<span class="price"></span>

最新更新