【问题标题】:JQuery ajax - how to pass an array parameter with null valueJQuery ajax - 如何传递具有空值的数组参数
【发布时间】:2021-10-31 04:41:55
【问题描述】:

我需要将一个数组参数传递给我的 ASP.NET 后端。 它看起来像这样:

$.ajax({ url: 'test', type: 'POST', data: { test: [1, 2] }})

而生成的表单数据为: test[]=1&test[]=2.

到目前为止一切顺利。但是当我尝试在数组中传递null 值时,就会出现问题:

$.ajax({ url: 'test', type: 'POST', data: { test: [1, null] }})

在这种情况下,由于某种原因生成的表单数据如下所示: test[]=1&test[1]=.

请注意第二个test 段有一个数字索引。这无法在后端正确解析:带索引的段被忽略,所以后端没有我的 null 值。

知道如何让它工作吗?

【问题讨论】:

  • 尝试使用 { test: [1, 0] } 或 { test: [1, -1] } 并在 API 内部转换回
  • @Serge 谢谢,我已经这样做了,但这只是一种解决方法,我想以更简洁的方式解决它。

标签: jquery ajax asp.net-mvc asp.net-mvc-ajax jquery-ajax


【解决方案1】:

我通过使用空字符串而不是null来解决它:

$.ajax({ url: 'test', type: 'POST', data: { test: [1, ''] }})

在这种情况下,表单数据如下所示:test[]=1&test[]=,并在后端正确解析为 1null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多