javascript - 从 html 字段中获取输入并将其存储在 JSON 对象中(很多输入字段)

标签 javascript jquery html ajax json

我正在寻找一种从 HTML 表单获取输入并将其存储到 JSON 对象中以用于 AJAX 的方法。我不能使用普通的 $('#id').val();,因为正如您在下面看到的那样,有很多字段。这是一些示例代码

Javascript/jQuery:

$(document).ready(function() {
    $('.add-to-cart').click(function() {
        var id = $(this).attr('id');
        //var qty = $(this).attr('qty'); <- need the quantity from the field 
        console.log(id);
        //console.log(qty);
        $.ajax({
            url: 'addproduct',
            type: 'POST',
            datazType: 'JSON',
            data: {
                "id": id
                //"qty": qty
            },
            success: function(addedproduct) {
                console.log(addedproduct.name);
                $('#cart').append('<li>'+ addedproduct.name +'</li>');
            },
            error: function() {
                console.log('failed to add product');
            }
        })
    });
});

HTML:

<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>

请帮助我,或者至少指导我正确的方向,这必须使用 AJAX 来实现。

最佳答案

jQuery 的 selialize方法就是你要找的。它序列化表单中的输入值。

有用的例子:https://stackoverflow.com/a/6960586/4180481

关于javascript - 从 html 字段中获取输入并将其存储在 JSON 对象中(很多输入字段),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28285405/

相关文章:

javascript - 必须有更好的方法 - 随着用户输入的变化而更改搜索

jquery 可以淡入淡出吗在视频中

jquery - 在移动设备上禁用垂直滚动(但不是水平滚动)

javascript - SelectBoxIt - 页面上的多个选择(动态)

php - 当我提交表单时,我的数据库不会插入我的记录

javascript - 表格内容不在下方

javascript - 获取 URL 的文件名和父文件夹

html - 在CSS/SVG中,如何旋转一个单词的每个字符?

javascript - 如何将移动物体与背景居中?

javascript - 在对象中使用数学运算