php jquery 序列化和 $.post
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/920294/
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
jquery serialize and $.post
提问by musoNic80
I'm trying to send a lot of data from a form using the $.post method in jQuery. I've used the serialize() function first to make all the form data into one long string which I will then explode serverside. The weird thing is when I try and send it using $.post it appends the result of the serialize() to the URL as if I was sending it using GET. Anyone have any ideas why this is happening?
我正在尝试使用 jQuery 中的 $.post 方法从表单发送大量数据。我首先使用了 serialize() 函数将所有表单数据制作成一个长字符串,然后我将在服务器端爆炸。奇怪的是,当我尝试使用 $.post 发送它时,它会将 serialize() 的结果附加到 URL 中,就像我使用 GET 发送它一样。任何人都知道为什么会发生这种情况?
Here's the jquery:
这是jquery:
$("#addShowFormSubmit").click(function(){
var perfTimes = $("#addShowForm").serialize();
$.post("includes/add_show.php", {name: $("#showTitle").val(), results: perfTimes }, function(data) {
$("#addShowSuccess").empty().slideDown("slow").append(data);
});
});
here's the php:
这是php:
$show = $_POST['name'];
$results = $_POST['results'];
$perfs = explode("&", $results);
foreach($perfs as $perf) {
$perf_key_values = explode("=", $perf);
$key = urldecode($perf_key_values[0]);
$values = urldecode($perf_key_values[1]);
}
echo $key, $values;
采纳答案by Jake Wilson
If you are using a <button>element to activate the serialize and ajax, and if that <button>element is within the formelement, the buttonautomatically acts as a form submission, no matter what other .click assignment you give it with jQuery.
如果您正在使用一个<button>元素来激活序列化和 ajax,并且如果该<button>元素在该form元素内,则button无论您使用 jQuery 给它什么其他 .click 分配,它都会自动充当表单提交。
type='submit'
类型='提交'
<button></button>and <button type='submit'></button>are the same thing. They will submit a form if placed within the <form>element.
<button></button>并且<button type='submit'></button>是一回事。如果放置在<form>元素中,他们将提交一个表单。
type='button'
类型='按钮'
<button type='button'></button>is different. It is just a normal button and will not submit the form (unless you purposely make it submit the form via JavaScript).
<button type='button'></button>是不同的。它只是一个普通的按钮,不会提交表单(除非你故意让它通过 JavaScript 提交表单)。
And in the case where a formelement has no action attribute specified, this submission simply sends the data back onto the same page. So you will end up seeing a page refresh, along with the serialized data appearing in the URL as if you used GET in your ajax.
在表单元素没有指定 action 属性的情况下,此提交只是将数据发送回同一页面。因此,您最终会看到页面刷新,以及出现在 URL 中的序列化数据,就好像您在 ajax 中使用了 GET 一样。
Possible solutions
可能的解决方案
1 - Make the <button>type button. As explained above, this will prevent the button from submitting the form.
1 - 制作<button>类型button。如上所述,这将阻止按钮提交表单。
Before:
前:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
<button id='mySubmitButton'>Submit</button>
</form>
After:
后:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
<button type='button' id='mySubmitButton'>Submit</button>
</form>
2 - Move the <button>element outside the <form>element. This will prevent the button from submitting the form.
2 - 将<button>元素移到元素外<form>。这将阻止按钮提交表单。
Before:
前:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
<button id='mySubmitButton'>Submit</button>
</form>
After:
后:
<form id='myForm'>
<!--Some inputs, selects, textareas, etc here-->
</form>
<button id='mySubmitButton'>Submit</button>
3 - Add in the preventDefault()into the button click handler to prevent the form from being submitted (it's default action):
3 - 添加preventDefault()到按钮单击处理程序中以防止提交表单(这是默认操作):
$("#addShowFormSubmit").click(function(event){
event.preventDefault();
var perfTimes = $("#addShowForm").serialize();
$.post("includes/add_show.php", {name: $("#showTitle").val(), results: perfTimes }, function(data) {
$("#addShowSuccess").empty().slideDown("slow").append(data);
});
});
Obviously without seeing all your code, I have no idea if this is the case for your issue, but the only reason I have ever seen behavior you are describing is because the submit button was a <button>without a type specified.
显然没有看到您的所有代码,我不知道您的问题是否属于这种情况,但我看到您描述的行为的唯一原因是因为提交按钮<button>没有指定类型。
回答by Franz
try using serializeArray() instead of serialize(). serialize() will produce an url-encoded query string, whereas serializeArray() produces a JSON data structure.
尝试使用 serializeArray() 而不是 serialize()。serialize() 将产生一个 url 编码的查询字符串,而 serializeArray() 产生一个 JSON 数据结构。
回答by Philippe Leybaert
What leads you to believe that the data is appended to the URL?
是什么让您相信数据已附加到 URL?
Anyway, wouldn't it make more sense to pass the form values in the form data itself? It will allow you to skip the "explode" step:
无论如何,在表单数据本身中传递表单值不是更有意义吗?它将允许您跳过“爆炸”步骤:
$("#addShowFormSubmit")
.click(function() {
var perfTimes = $("#addShowForm").serialize();
$.post("includes/add_show.php",
$.param({name: $("#showTitle").val()}) + "&" + perfTimes,
function(data) {...});
});
回答by Vassi
So this is probably a bit obtuse, but I made a function to help me do this very thing since I got tired of making a bunch of fixes every time. serializeArray is kind of annoying because it provides a collection of objects, when all I wanted to have PhP reconstruct was an associative array. The function below will go through the serialized array and will build a new object with the appropriate properties only when a value exists.
所以这可能有点迟钝,但我做了一个函数来帮助我做这件事,因为我厌倦了每次都做一堆修复。serializeArray 有点烦人,因为它提供了一组对象,而我只想让 PhP 重建一个关联数组。下面的函数将遍历序列化数组,并仅在值存在时构建具有适当属性的新对象。
Firstly, the function (it takes the ID of the form in question):
首先,函数(它采用相关表单的 ID):
function wrapFormValues(form) {
form = "#" + form.attr("id") + " :input";
form = $(form).serializeArray();
var dataArray = new Object();
for( index in form)
{
if(form[index].value) {
dataArray[form[index].name] = form[index].value;
}
}
return dataArray;
}
When constructing my posts I also usually use an object since I usually tag on two or three other values before the form data and I think it looks cleaner than to define it inline, so the final step looks like this:
在构建我的帖子时,我通常也使用一个对象,因为我通常在表单数据之前标记两个或三个其他值,而且我认为它看起来比内联定义它更清晰,所以最后一步看起来像这样:
var payload = new Object();
//stringify requires json2.js from http://www.json.org/js.html
payload.data = JSON.stringify(data);
$.post("page.php", payload,
function(reply) {
//deal with reply.
});
Server-side all you have to do is $payload = json_decode($_POST['data'], true)and you have yourself an associative array where the keys are the names of your form fields.
在服务器端,您所要做的就是$payload = json_decode($_POST['data'], true)拥有一个关联数组,其中的键是表单字段的名称。
Full disclaimer though, multiple-selects probably won't work here, you would probably only get whichever value was last on the list. This is also created very specifically to suit one of my projects, so you may want to tweak it to suit you. For instance, I use json for all of my replies from the server.
完全免责声明,多选可能在这里不起作用,您可能只会获得列表中最后一个值。这也是专门为适合我的一个项目而创建的,因此您可能需要对其进行调整以适合您。例如,我对来自服务器的所有回复都使用 json。
回答by Zacho
Try this syntax. I use this to serialize a form and POST via ajax call to WCF service. Also, you can send this back a single JSON object instead of building the object the way you are. Try this:
试试这个语法。我使用它通过对 WCF 服务的 ajax 调用来序列化表单和 POST。此外,您可以将其发送回单个 JSON 对象,而不是按照您的方式构建对象。尝试这个:
var serializedForm = serializedForm = $("#addShowForm").serializeArray();
$.post("includes/add_show.php",
{
"myObjectName": ("#showTitle").val(), results: perfTimes
}, function(data)
{
$("#addShowSuccess").empty()
.slideDown("slow")
.append(JSON.stringify(serializedForm));
});
回答by Chris Rasco
回答by Jake Wilson
One more possible reason for this issue: If you have a form without any sort of submission action assigned to it, whenever you press the "ENTER" key while filling out the form, the form will be submitted to the current URL, so you will see the serialized data appear in the URL as if you were using a GET ajax transaction. A simple solution to this problem, just prevent ENTER from submitting the form when its pressed:
此问题的另一个可能原因:如果您的表单没有分配任何类型的提交操作,则每当您在填写表单时按“ENTER”键,表单将被提交到当前 URL,因此您将看到序列化数据出现在 URL 中,就像您使用 GET ajax 事务一样。这个问题的一个简单解决方案,只是阻止 ENTER 在按下时提交表单:
//Prevent Form Submission when Pressing Enter
$("form").bind("keypress", function(e) {
if (e.keyCode == 13)
return false;
});

