开发者

jQuery fails to send arrays as JSON content type

开发者 https://www.devze.com 2023-02-26 16:22 出处:网络
I\'m using a script that looks like this: $.ajax({ url: \'myservice\', type: \'POST\', contentType: \'application/json\',

I'm using a script that looks like this:

$.ajax({
    url: 'myservice',
    type: 'POST',
    contentType: 'application/json',
    data: ["test"],
});
开发者_StackOverflow中文版

However this causes a request to myservice/?undefined=undefined which probably indicates that jQuery is assuming data to be a map. Is there any way around this? Is there a way to serialize data manually (preferably without resorting to any 3rd party libraries)?

I tested my service manually and it works correctly with the data like ["test"].

EDIT: A bug concerning request method.

EDIT(2): Interesting, now it causes 400 Bad request. However if I switch to '["test"]' (a string) it works. I use jQuery 1.5.2.


change method: 'POST' to type: 'POST'

doc | example

Edit: for data you should use either query string example=test&examplex=test2 or javascript object {example: "test", examplex: "test2"}


$.ajax({
    url: 'myservice',
    method: 'POST',
    contentType: 'application/json',
    data: '["test"]',
});

Note that you need to pass in the json as a string.

If your json is complicated you can always use Crockford's stringify.


data should be an object like:

{var1: 'test', var2: 'test'}

Also, I think you can make your contentType just: 'json'

If you need to serialize a form and send in the values, jQuery has a function for that:

$("formId").serialize();

see This Link

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号