gpt4 book ai didi

javascript - 如何使用 ajax 将与每个按钮相关的数据发送到 php?

转载 作者:行者123 更新时间:2023-11-30 12:31:04 32 4
gpt4 key购买 nike

我知道像这样的代码用于将数据发送到 php 文件而不使用 ajax 刷新,但这段代码仅适用于具有某些输入的一种表单,我的问题是:我有一个网页,里面有 5 个按钮,每个按钮都与不同的输入相关,我想用 ajax 发送数据而不刷新,例如当我点击按钮 1 时,它发送自己的输入,当我点击按钮时n 它发送自己的数据,我该怎么做?

<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {

$('form').on('submit', function (e) {

e.preventDefault();

$.ajax({
type: 'post',
url: 'led.php',
data: $('form').serialize(),
success: function () {
}
});

});

});
</script>
</head>
<body>
<form>
<input type='hidden' name="key" value="on">
<input name="key" type="submit" value="ON">
</form>
</body>
</html>

最佳答案

" but this code only works for one form with some inputs "

从技术上讲,这将适用于页面上的任何表单。 (因为您的目标是 form 标签)

如果您想定位多个按钮并以相同的方式处理它们,请向它们添加一个类。

如果您想单独定位单独的元素,请添加一个 id。

然后您将类定位为 $('.classname') 并将 id 定位为 $('#id') 注意 .和 #(与 css 选择器一样)

SEE LIVE EXAMPLE here

$('.submit_to_a').parent('form').on('submit', function(e) {

e.preventDefault();

$.ajax({
type: 'post',
url: 'a.php',
data: $(this).serialize(),
success: function() {}
});

});


$('#gotob').parent('form').on('submit', function(e) {

e.preventDefault();

$.ajax({
type: 'post',
url: 'b.php',
data: $(this).serialize(),
success: function() {}
});

});

$('#gotoc').parent('form').on('submit', function(e) {

e.preventDefault();

$.ajax({
type: 'post',
url: 'c.php',
data: $(this).serialize(),
success: function() {}
});

});
<form action="a.php">
<input type="text">
<input type="text">
<input type="text">
<button type="submit" class="submit_to_a">goes to a</button>
</form>
<form action="a.php">
<input type="text">
<input type="text">
<input type="text">
<button type="submit" class="submit_to_a">goes to a</button>
</form>
<form action="b.php">
<input type="text">
<input type="text">
<input type="text">
<button type="submit" id="gotob">goes to b</button>
</form>
<form action="c.php">
<input type="text">
<input type="text">
<input type="text">
<button type="submit" id="gotoc">goes to c</button>
</form>

关于javascript - 如何使用 ajax 将与每个按钮相关的数据发送到 php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27676052/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com