gpt4 book ai didi

javascript - jquery通过ajax传递单值数组

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:27 25 4
gpt4 key购买 nike

我看过很多关于如何在jquery中通过ajax传递数组的帖子。这不完全是关于这些问题。以下行为是合理的还是我做错了什么?

我有一些简单的jquery ...

var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
url: url,
data: {
ids: changedIds
},
dataType: "json",
traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
console.log("Submit Fail: ");
});

changedIds 数组最终将包含 0-N 个整数。我在 POST 之前检查 .length,因此不会发送零长度数组。我的问题是当只有一个值时会发生什么。

看起来,拥有单值数组会将“数组”视为普通变量。 HTTP 请求列出的数据如下:

ids=123

此 ajax 调用的目标是需要数组值的 .Net ActionResult 方法。如果它被传递给看起来像普通变量的东西,它就会噘嘴并抛出异常。

我已经开始检查数组.length,如果它是1,则插入一个已知的虚拟值,以便该数组有两个值。这似乎可行——但是这是正确的行为吗?这是最好的解决方法吗?

最佳答案

尝试使用 JSON.stringify 序列化您的数据参数,并指定 application/jsoncontentType,如下所示:

var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
url: url,
data: JSON.stringify({
ids: changedIds
}),
contentType: "application/json",
dataType: "json",
traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
console.log("Submit Fail: ");
});

这应该将 JavaScript 对象转换为有效的 JSON,并告诉服务器您要发送的数据类型。

关于javascript - jquery通过ajax传递单值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41769065/

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