将每个输入名称和值传递给ajax GET

时间:2017-08-02 15:46:56

标签: javascript php jquery ajax

今天我试图遍历每个文本框,其id为setting_value,并将其名称和值设置为键值数组,然后传递给ajax请求。

问题是,它只查看ID的第一次出现,有人知道为什么吗?

这是JS

function saveSettings() {
    var myFieldsValue = {};
    $("#setting_value").each(function() {
        myFieldsValue[this.name] = $(this).val();
        alert(this.name + ' = ' + $(this).val());
    });

    $.ajax({
        url: '/' + 'api/ajax/higher/save_game_settings',
        type: "GET",
        data: myFieldsValue,
        statusCode: {
            400: function (response) {
                showErrorNotification("Something went wrong", response.responseText, 3000);
            },
            500: function (response) {
                showErrorNotification("Something went wrong", response.responseText, 3000);
            }
        },
        success: function(data) {
            showSuccessNotification("Action Completed", "Settings have been updated.", 1000);
        }
    });
}

这是HTML

<div class="ibox-content" style="">
    <h2>Main Game Settings</h2>
    <p>Mainline In-Game configuration</p>
    <hr>
    @foreach($gameSettings as $key => $setting)
    <div class="row">
        <div class="col-md-6">
            <b>{{ $setting->setting_key }}</b><br>
            {{ $setting->setting_description }}
        </div>
        <div class="col-md-6">
            <input type="text" id="setting_value" name="{{ $setting->setting_key }}" value="{{ $setting->setting_value }}" class="form-control">
        </div>
    </div>
    <hr>
    @endforeach
    <div class="btn btn-info" onclick="saveSettings();">Save Changes</div>
</div>
</div>

1 个答案:

答案 0 :(得分:3)

元素ID应该是唯一的。它们是唯一标识符。因此$("#setting_value")只会返回一个元素。如果要匹配一组元素,请使用类,例如

class="setting_value"
$(".setting_value")