jQuery .serialize() 和 .serializeArray() 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10430502/
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
What's the difference between .serialize() and .serializeArray()?
提问by kaze
I'm experimenting with sending a form to a controller. jQuery documentation says that .serializeArray()
should send a json array, and .serialize()
should create a query string.
我正在尝试向控制器发送表单。jQuery 文档说.serializeArray()
应该发送一个 json 数组,并且.serialize()
应该创建一个查询字符串。
However, when I try it, and inspecting with IE9 F12-mode, it looks like a query string, in both cases. Which ever call I make...
但是,当我尝试并使用 IE9 F12 模式进行检查时,在这两种情况下,它看起来都像一个查询字符串。我打过哪个电话...
What am I missing?
我错过了什么?
回答by Jon
serializeArray
creates an array (nota "json array" -- there is no such thing); you can test this yourself with console.log($("#myform").serializeArray())
. On the other hand, serialize
creates a query string that's meant to be part of an HTTP request. Both representations are equivalent in the sense that using appropriate code you can convert one to the other without any ambiguity.
serializeArray
创建一个数组(不是“json 数组”——没有这样的东西);你可以用console.log($("#myform").serializeArray())
. 另一方面,serialize
创建一个查询字符串作为 HTTP 请求的一部分。这两种表示在某种意义上是等效的,即使用适当的代码可以将一种转换为另一种而不会产生任何歧义。
The reason for both versions being available is that serialize
is more convenient when you just want to make an HTTP request (just put the result in the query string) while serializeArray
is more convenient if you want to process the results yourself.
两个版本都可用的原因serialize
是当您只想发出 HTTP 请求(只需将结果放在查询字符串中)时serializeArray
更方便,而如果您想自己处理结果则更方便。
jQuery's AJAX methods don't care if you give them one or the other because they detect the type of the parameter and convert it to a query string if it's not one already, so by the point the request is made outside observers cannot tell what was the original format of the parameters.
jQuery 的 AJAX 方法不在乎您是否给它们一个或另一个,因为它们检测参数的类型并将其转换为查询字符串(如果它不是一个),因此当请求是在外部观察者发出时无法分辨是什么参数的原始格式。