[英]jquery passing single value arrays via ajax
I've seen a lot of posts about how to pass arrays via ajax in jquery.我看过很多关于如何在 jquery 中通过 ajax 传递数组的帖子。 This is not exactly about those questions.这不完全是关于这些问题。 Is the following reasonable behaviour or am I doing something wrong?以下是合理的行为还是我做错了什么?
I have some simple jquery ...我有一些简单的 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: ");
});
The changedIds
array will end up with 0-N integers in it. changedIds
数组最终将包含 0-N 个整数。 I check the .length
before the POST so a zero length array is not sent.我在 POST 之前检查.length
,因此不发送零长度数组。 My question is about what happens when there is only ONE value.我的问题是当只有一个值时会发生什么。
It appears that having a single value array treats the "array" like a plain variable.似乎具有单值数组将“数组”视为普通变量。 The HTTP request lists the data as: HTTP 请求将数据列为:
ids=123
The target of this ajax call is a .Net ActionResult
method that wants an array value.这个 ajax 调用的目标是一个需要数组值的 .Net ActionResult
方法。 It pouts and throws an exception if it is handed what looks like a plain variable.如果它被传递给一个看起来像普通变量的东西,它就会噘嘴并抛出一个异常。
I have started checking the array .length
and if it is 1 then pushing in a known dummy value so that there are two values for the array.我已经开始检查数组.length
,如果它是 1,则推入一个已知的虚拟值,以便数组有两个值。 This seems to work -- but is this correct behaviour?这似乎有效——但这是正确的行为吗? Is this the best work-around?这是最好的解决方法吗?
Try serializing your data parameter using JSON.stringify
and specifying a contentType
of application/json
as follows:尝试使用JSON.stringify
序列化您的数据参数并指定application/json
的contentType
,如下所示:
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: ");
});
That should convert the JavaScript object into valid JSON and tell the server the type of data that you are sending.这应该将 JavaScript 对象转换为有效的 JSON 并告诉服务器您发送的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.