.serialize() an array of variables in Javascript

为君一笑 提交于 2019-12-24 14:28:43

问题


I have a list of variables available to me and I want to send it via $.ajax post. What format would I have to keep these in to use the function .serialize? I keep getting this error:

Object 'blank' has no method 'serialize'

I've tried to make them an array and I've tried jQuery.param(). I have a feeling this is simple but I can't seem to get it. Thanks!

var $data = jQuery.makeArray(attachmentId = attachmentID, action = 'rename', oldName = filename, newName, bucketName, oldFolderName, newFolderName, projectId = PID, businessId = BID);
var serializedData = $data.serializeArray();
//alert(theurl);

$.ajax({ type: "post", url: theurl, data: serializedData, dataType: 'json', success:  reCreateTree });  

回答1:


.serialize is for form elements:

Encode a set of form elements as a string for submission.

The $.ajax documentation says for the data option:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

So all you need to do is passing an object. For example:

$.ajax({ 
    type: "post", 
    url: theurl, 
    data: {                             // <-- just pass an object
          attachmentId: attachmentID,
          action: 'rename',
          // ...
    },
    dataType: 'json', 
    success:  reCreateTree 
});  



回答2:


It seems you're used to the PHP style of array's (associated arrays). In Javascript, objects are basically the same thing (though can be MUCH more complicated).

So if you are trying to create an array like this in php it would be

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

in Javascript using an object instead of an array it would be

var arr = {
    foo: "bar",
    bar: "foo"
}


来源:https://stackoverflow.com/questions/10818000/serialize-an-array-of-variables-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!