【问题标题】:AJAX post with jQuery changing the name of an array parameter使用 jQuery 更改数组参数名称的 AJAX 帖子
【发布时间】:2011-05-04 18:17:41
【问题描述】:

我正在使用 jQuery 做一个简单的 AJAX 帖子,效果很好:

var parameters = {firstName: 'John', lastName: 'Smith'};
$.post('http://api.example.com/rest', parameters, function(data) {
  alert('Response: ' + data.someResult);
});

但是,当我像这样向参数添加数组时:

var parameters = {firstName: 'John', lastName: 'Smith', children: ['Susy', 'Billy']};

那么问题是参数名称children 被更改为children[](它实际上是URL 编码为children%5B%5D)当POST 到服务器时。我无法更改服务器以查找名称为 children[] 的参数,我该怎么办?如何发布多个名称为 children 的值?为什么 jQuery 会更改我的参数名称?

【问题讨论】:

    标签: ajax jquery post parameters


    【解决方案1】:

    相信你需要开启traditional参数编码。

    http://api.jquery.com/jQuery.ajax/http://api.jquery.com/jQuery.param

    由于$.post 对此没有特定选项,您需要恢复为$.ajax 或使用全局设置jQuery.ajaxSettings.traditional = true

    【讨论】:

    • 好的,谢谢!我担心设置这样的全局值可能会干扰我网页上的其他 3rd 方脚本?所以我将只使用 $.ajax 机制。
    • 你也可以调用jQuery.param(parameters, true),在你当前传递原始parameters的地方传递结果:jQuery.param()
    猜你喜欢
    • 2023-03-23
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2014-08-06
    相关资源
    最近更新 更多