我正在尝试获取前9个单击按钮的值,并将它们放入名为$u_input
的数组中。我实际上找到了this,但它在javascript中。
我的HTML
<div>
<button name="btn1" type="submit" id="btn1" value="1" style="width:50%;height:40%;margin-left: auto;margin-right: auto; float:left" class="ui-btn"></button>
<button name="btn2" type="submit" id="btn2" value="2" style="width:50%;height:40%;margin-left: auto;margin-right: auto;float:right" class="ui-btn"></button>
</div> // I have up to 9 buttons, thats only a piece
我的javascript:
$(document).ready(function(){
$('.ui-btn').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'escreen.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
});
我的php:
if (isset($_POST['action'])) {
$u_input = array($_POST['action'](1), $_POST['action'](2), $_POST['action'](3), $_POST['action'](4));
echo $u_input;
}
答案 0 :(得分:2)
使用以下代码循环浏览按钮:
jQuery(document).ready(function($){
var ajaxurl = 'escreen.php',
$values = [];
$('button').each(function(){
$values.push($(this).val());
});
$.ajax({
url: ajaxurl,
type: 'post',
data: {
buttons: $values,
},
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
});
更好的方法是为数组中的每个属性设置一个名称:
jQuery(document).ready(function($){
var ajaxurl = 'escreen.php',
$values = [];
$('button').each(function(){
$values[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: ajaxurl,
type: 'post',
data: {
buttons: $values,
},
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
});
数组$values
应包含以下内容:
[button1: "value1", button2: "value2", button3: "value3"]
因此,在PHP文件中,您可以使用以下命令对其进行检索:
$_POST['buttons']['button1']