首页 > 解决方案 > 使用表单发布发布对象数组的正确方法

问题描述

我正在尝试在我的应用程序中使用支付服务 API,并遵循网站上提供的文档。根据文档,POST 正文应如下所示:

api_hash=38be425a-63d0-4c46-8733-3e9ff662d62d
&hash=ac0945d82b8589959b5f4ffafcc1a6c5983e82b8b4094c377a7b9c43d4a432bc
&order_id=2845
&amount=15
&currency=EUR
&email=stefan@my-test-store.com
&url_failure=http://my-test-store.com/order/fail
&url_ok=http://my-test-store.com/order/success
&items=[{"sku":"450","name":"Test Item","amount":"15","type":"item_type","qty":"1","price":15,"id":"5619","url":"http://example.com/products/item/example-item-name-5619"}]

我能够成功地向邮递员发出帖子请求,但是我对帖子正文中的“项目”部分感到困惑,因为它是一个对象数组。我的 html 表单如下所示:

<form method="post" action="@ViewBag.G2AConfig.PostUrl" id="g2apaymentform">
    <!--PayPal Settings-->
    <input type="hidden" name="api_hash" value="@ViewBag.G2AConfig.ApiHash" />
    <input type="hidden" name="hash" value="@ViewBag.Hash" />
    <input type="hidden" name="order_id" value="@ViewBag.OrderId" />
    <input type="hidden" name="amount" value="@Model.Total" />
    <input type="hidden" name="currency" value="USD" />
    <input type="hidden" name="email" value="@ViewBag.G2AConfig.MerchantEmail" />
    <input type="hidden" name="url_failure" value="@ViewBag.UrlFailure" />
    <input type="hidden" name="url_ok" value="@ViewBag.G2AConfig.ReturnUrl" />

    @foreach (var item in Model.Items)
    {
        <input type="hidden" name="items[@index][sku]" value="@item.Product.GameAccountId" />
        <input type="hidden" name="items[@index][name]" value="@item.Product.Rank.Name" />
        <input type="hidden" name="items[@index][amount]" value="@item.Product.MarketPrice" />
        <input type="hidden" name="items[@index][qty]" value="1" />

        index = index + 1;
    }
</form>

我正在使用 Ajax 发布请求,如下所示:

event.preventDefault(); //prevent default action 
                    var post_url = $(this).attr("action"); //get form action url
                    var request_method = $(this).attr("method"); //get form GET/POST method
                    var form_data = $(this).serialize(); //Encode form elements for submission

                    $.ajax({
                        url: post_url,
                        type: request_method,
                        data: form_data
                    }).done(function (response) { //
                        $("#server-results").html(response);
                    });

这不起作用,我从服务器收到错误的错误响应。提交带有对象数组的表单的正确方法是什么?

标签: htmlajaxasp.net-mvchttppost

解决方案


为什么在发布之前使用假定的对象创建一个表单?

如果除了发布值之外没有其他真正的原因,那么我建议您通过 javascript 数组构建 AJAX 数据,或者PlainObject因为这些是 data 参数的其他 2 种可能的数据类型。目前您正在使用序列化字符串。


推荐阅读