gpt4 book ai didi

javascript - 在 POST 上将 javascript 对象读取为 JSON

转载 作者:行者123 更新时间:2023-12-03 17:06:26 24 4
gpt4 key购买 nike

我在其他 SO 帖子中读到“javascript is JSON”。我很难将这个理论转化为我的应用程序。我用 jQuery 执行 POST

    $.ajax({
type: 'POST',
url: 'Pricing/Create',
data: items,
success: function () { alert('successfully called pricing'); },
dataType: 'json'
});

帖子成功命中了我的PricingControllerCreate 方法中的断点。在查看我的 Request.QueryString 时,它是空的。

itemsSomeItem 的数组,length = 30。定义为

function SomeItem(description, finalPrice, percentDiscount) {
this.Description = description;
this.FinalPrice = finalPrice;
this.PercentDiscount = percentDiscount;
}

我不执行 JSON 转换,因为“javascript 是 JSON”。如何在定价 Controller 中获取我的数据?


差不多了。当 JSON.stringify(items) 运行时,我在我的 alert() 中看到一组不错的垃圾(在 Firebug 中也很漂亮):

[{"Description":"some item","Data2":"$1.00","data3":"10"},//...

但是,当它到达服务器时...在 C# Request.Form 中它看起来像:

%5b%7b%22Description%22%3a%22some+item%22%2c%22data2%22 wtflip 是...

最佳答案

JSON 是“JavaScript 对象表示法”,而不是 JavaScript。您使用 JSON 来表示 JavaScript 对象,尤其是当您要将其发送回服务器时。

在将 JavaScript 对象传递给 ajax 调用之前,您确实需要将其转换为 JSON - 这应该可以解决问题:

var json = $.toJSON(items);

读一读,可能会有帮助:http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

关于javascript - 在 POST 上将 javascript 对象读取为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7407423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com