使用jQuery更改数组参数名称的AJAX帖子

问题描述:

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

I'm doing a simple AJAX post using jQuery, works great:

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

然而,当我像这样添加一个数组:

However, when I add an array to the parameters like so:

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

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

Then the problem is the parameter name children gets changed to children[] (it's actually URL encoded to children%5B%5D) when POSTing to the server. I can't change the server to look for parameters with the name children[] so what do I do? How can I POST multiple values with the name children? Why is jQuery changing the name of my parameter?

我相信你需要启用传统

code>参数编码。

I believe you need to enable traditional parameter encoding.

请参阅 http://api.jquery.com/jQuery.ajax/ http:// api。 jquery.com/jQuery.param

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

As $.post doesn't have a specific option for this you'll either need to revert to $.ajax or use the global setting jQuery.ajaxSettings.traditional = true.