.serialize() Javascript 中的变量数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10818000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:08:37  来源:igfitidea点击:

.serialize() an array of variables in Javascript

javascriptjqueryserialization

提问by Lucas SenCab A Ugh

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:

我有一个可用的变量列表,我想通过 $.ajax 帖子发送它。我必须保留什么格式才能使用 .serialize 函数?我不断收到此错误:

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!

我试图让它们成为一个数组,我也尝试过 jQuery.param()。我觉得这很简单,但我似乎无法理解。谢谢!

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 });  

回答by Felix Kling

.serializeis for form elements:

.serialize用于表单元素

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

将一组表单元素编码为字符串以供提交。

The $.ajaxdocumentationsays for the dataoption:

$.ajax文件说,该data选项:

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 processDataoption 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).

要发送到服务器的数据。如果不是字符串,则将其转换为查询字符串。它附加到 GET 请求的 url。请参阅processData防止此自动处理的选项。对象必须是键/值对。如果 value 是一个数组,jQuery 会根据传统设置的值(如下所述)序列化具有相同键的多个值。

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 
});  

回答by b.kelley

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).

看来您已经习惯了数组(关联数组)的 PHP 样式。在 Javascript 中,对象基本上是一样的东西(尽管可能要复杂得多)。

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

因此,如果您尝试在 php 中创建这样的数组,它将是

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

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

在 Javascript 中使用对象而不是数组

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