问题
I'm using a plugin to do a non-Ajax post. However, my array is just submitted with "[Object = object]", so I clearly need to do some parameterization on this array object. It's not as simple as putting it in a hash like:
{ 'myarray': myarray }
When you send the above to $.ajax(), it changes it to something like:
{ 'myarray': {'1': arrayfirsthash, '2': arraysecondhash, ...., '3': arraynhash } }
There must be some jQuery function that does that conversion. What is it, and can I call it publicly?
Thanks for any help you can offer.
UPDATE: To clarify my question, I'm actually looking to see how I can place this value in a form element so that it will be understood as a hash by the server. Even if I place the JSON-encoded hash in a form element, it still comes out as "Object" by the server. I need to somehow serialize this JSON hash so that it can be POSTED to my server.
回答1:
The format of the parameters will depend upon whether you are performing a GET or a POST operation.
If you are performing a POST then the parameters are sent within the message body.
If the service is expecting the information in JSON, you will have to explicitly serialize the data before passing it into your .ajax call (as the 'data' parameter).
It can be serialized this way:
contentSerialized = JSON.stringify(content);
The JSON.stringify
function is only supported by later browsers.
I believe there are some javscript plugins you can download which "spak-fill" this functionality - enabling this for browsers that don't support it. See this question.
If you are performing a web GET then the parameters are encoded into the query string.
The .ajax call will perform this encoding automatically, but it you wanted to do this explicitly jQuery provides the .param function.
回答2:
I believe you want create a parameter string from an object. To do this you can use $.param()
: http://api.jquery.com/jquery.param/
Here is a jsfiddle of using $.param()
on an object: http://jsfiddle.net/jasper/eVLVJ/
var myObject = {
a: { one: 1, two: 2, three: 3 },
b: [1, 2, 3] };
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));
alert(recursiveDecoded);
Note: the above code is an example on the documentation page for $.param()
.
来源:https://stackoverflow.com/questions/8319766/how-does-jquery-parameterize-an-array-in-ajax