【问题标题】:insert values of clicked buttons into array将点击按钮的值插入数组
【发布时间】:2015-11-07 12:33:08
【问题描述】:

我正在尝试获取前 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;  
}

【问题讨论】:

  • 更改:&lt;button id="btn-1"&gt; value-1 &lt;/button&gt;

标签: php arrays ajax


【解决方案1】:

只需使用以下代码遍历按钮:

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']

【讨论】:

  • 感谢您的回答!我想我采用第一个代码 sn-p,因为我有 9 个不同的按钮,我只需要一个带有数字的数组。 :)
  • 好吧,不过你不应该使用$_POST['buttons']['button1'],而应该使用$_POST['buttons']
  • 如何在 php 中回显结果数组? :D
  • 如果我是对的,如果你使用选项 1,你可以使用 echo $_POST['buttons'][0],或者只是做一个 var_dump($_POST['buttons']) 看看发生了什么。或者做一个foreach($_POST['buttons'] as $k =&gt; $v){ var_dump($v); }
猜你喜欢
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
相关资源
最近更新 更多