Why does serialize() have the same effect as serializeArray() when setting post data for jQuery.ajax()?

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

i have this jQuery-AJAX code below and a form:

<script type="text/javascript"> $(document).ready(function () {     $('form').submit(function () {         form_data = $(this).serializeArray();          $.ajax({             url: "/frontend_dev.php/coche1/update/id/1",             type: "POST",             data: form_data              });         });         return false;  }); </script> 

As you can see I'm using serializeArray() but when i use serialize() it also works the same..

Why in both cases works the same? What of them should i use?

Im using symfony as php framework. I can offer you more info if you need it.

回答1:

If an object/array gets passed (which .serializeArray() returns), it's serialized via $.param().

If a string get passed (which .serialize() returns) it doesn't do anything further.

...so they have the same effect when passed as the data property. You can find the relevant check here:

    // convert data if not already a string     if ( s.data && s.processData && typeof s.data !== "string" ) {         s.data = jQuery.param( s.data, s.traditional );     } 

Which one should you use? It really doesn't matter here, .serialize() makes the same $.param() call, so they do the exact same amount of work. I personally use .serialize() because it's simply less to type.



回答2:

In this case, they're the same. But there is a big difference if you do not specify the type - serialize will do a GET and serializeArray will do a POST!



回答3:

I've noticed that in CodeIgniter, the .serialize method can produce data that gets polluted by CodeIgniter's CSRF protection (CodeIgniter somehow adds semi-colons to the array keys), whereas the forms I've submitted with .serializeArray did not have this problem.

Also, if you're using complex POST names, e.g. name="some[a][data][structure]" where the places in the $_POST array changes and are not arbitrary, then using .serialize will probably be much easier because you can convert it back into a PHP data structure much more easily.



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