【问题标题】:Take input from html field and store it in JSON object (lots of input fields)从 html 字段获取输入并将其存储在 JSON 对象中(大量输入字段)
【发布时间】:2015-02-03 03:42:20
【问题描述】:

我正在寻找一种从 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 来实现。

【问题讨论】:

  • 您可以使用属性选择器获取所有类型编号的输入,然后使用循环构建一个 javascript 对象。
  • 您希望 JSON 采用什么格式?另外,你说"as you can see below, there are a lot of fields",但我只看到一个&lt;input&gt;。 . .你错过了一些代码吗?

标签: javascript jquery html ajax json


【解决方案1】:

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

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

【讨论】:

  • 我实际上最终使用了你的方法,它更干净,项目升级很快,你的扩展性更好。
猜你喜欢
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多