【问题标题】:How to pass a variable in button id and then send that id to ajax data?如何在按钮 id 中传递一个变量,然后将该 id 发送到 ajax 数据?
【发布时间】:2019-03-23 21:04:40
【问题描述】:

我将产品的 id 传递给按钮 id,然后通过 Ajax 数据,我将该产品 id 发送到控制器

for(var i=0;i<productsJSON.length;i++)
{
    var td5 = document.createElement('td');
    td5.innerHTML = "<br><button type='button' id="+product.id+"onclick='Addtocart() ' >Add To Cart</button><br>";
}

function Addtocart() {

    var quantity = document.getElementsByName("quantity").item(0).value;

    $.ajax({
        type: "POST",
        data: 'pid=' + this.id + '&quantity=' + quantity,
        url: "ProductController",
        success: function(content) {
            console.log(content);
            alert('done');
        }
    });

}

【问题讨论】:

  • 您要发送哪个变量?运行代码时会发生什么?有错误吗?如果是这样,究竟是什么错误?

标签: json ajax model-view-controller


【解决方案1】:

您必须使用 JSON 对象。 这里我使用 GET 方法从 HTML 表单中设置数据。

$.ajax(
        {
            type: "GET",
            data: $("#form").serialize(),
            url: "url",
            success: function(data)
            {
                # Code
            },
            error: function()
            {
                # Code
            }
        }
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多