php 如果输入元素是数组,如何使用 JQuery 发送序列化表单数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/304518/
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
How to send serialize form data using JQuery if the input element is an array
提问by
I have this piece of code in my PHP code:
我的 PHP 代码中有这段代码:
while ($row = mysqli_fetch_assoc($result))
{
extract($row);
echo "<tr>";
echo "<td bgcolor='#FFFFFF'><input id='bookArray[]' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>";
echo "<td bgcolor='#FFFFFF'>$threat_name</td>";
echo "</tr>";
}
In HTML page, I want to use jQuery serialize() method to sent array of selected books in bookArray[]. In my JavaScript,
在 HTML 页面中,我想使用 jQuery serialize() 方法发送 bookArray[] 中选定书籍的数组。在我的 JavaScript 中,
var selectedbooks = $("book_form").serialize();
alert (selectedbooks);
In the alert message box, i did not get any value (empty string).
在警报消息框中,我没有得到任何值(空字符串)。
Previously when i am using Prototype, it worked nicely.
以前当我使用 Prototype 时,它工作得很好。
回答by
easy: serialize().replace(/%5B%5D/g, '[]')
简单: serialize().replace(/%5B%5D/g, '[]')
回答by Hailwood
I have come up with a method that will, when the data is sent using post
我想出了一种方法,当使用 post 发送数据时
on the other side lets you access your elements using $_['post']['name']
另一方面,您可以使用 $_['post']['name']
If it is an array (eg a multiple select) then on your server you can access it as an array again $_POST['myselect'][0]...
如果它是一个数组(例如多选),那么在您的服务器上,您可以再次将其作为数组访问 $_POST['myselect'][0]...
Code: Function to serialize form data for post
代码: 用于序列化表单数据以供发布的函数
function serializePost(form) {
var data = {};
form = $(form).serializeArray();
for (var i = form.length; i--;) {
var name = form[i].name;
var value = form[i].value;
var index = name.indexOf('[]');
if (index > -1) {
name = name.substring(0, index);
if (!(name in data)) {
data[name] = [];
}
data[name].push(value);
}
else
data[name] = value;
}
return data;
}
回答by Gafitescu Daniel
var arTags = new Array();
jQuery.map( $("input[name='tags[]']") , function(obj,index)
{
arTags .push($(obj).val());
});
var obj = {'new_tags' : $("#interest").val() ,
'allready_tags[]' : arTags };
var post_data = jQuery.param(obj,true);
$.ajax({
type : 'POST',
url : 'some_url',
data : post_data,
dataType : "html",
success: function(htmlResponse)
{
}
});
回答by Philo
jQuery 1.4
jQuery 1.4
var myform = $("book_form").serialize();
decodeURIComponent(myform);
回答by Deniska Axe
work correctly jquery =>
正常工作 jquery =>
var data = $('form').serialize();
$.post(baseUrl+'/ajax.php',
{action:'saveData',data:data},
function( data ) {
alert(data);
});
php =>
php =>
parse_str($_POST['data'], $searcharray);
echo ('<PRE>');print_r($searcharray);echo ('</PRE>');
output =>
输出 =>
[query] =>
[search_type] => 0
[motive_note] =>
[id_state] => 1
[sel_status] => Array
(
[8] => 0
[7] => 1
)
and You can do whatever what you want like with array data, thanks to Aridane https://stackoverflow.com/questions/1792603
并且你可以对数组数据做任何你想做的事情,感谢Aridane https://stackoverflow.com/questions/1792603
回答by Deniska Axe
Prototype / Scriptaculous serialize functionality for jQuery:
jQuery 的原型/Scriptaculous 序列化功能:
<script>
function toObjectMap( queryString )
{
return '{\'' + queryString.replace(/=/g, '\':\'').replace(/&/g, '\',\'') + '\'}';
}
</script>
...
<div id="result"></div>
...
<form onSubmit="$('#result').load( ajaxURL, toObjectMap( $('#formId').serialize() ) );" ...>
...
回答by Deniska Axe
@Tomalak You can use the square brackets characters "[" and "]" within XHTML see http://www.w3.org/TR/xhtml1/dtds.html#dtdentry_xhtml1-transitional.dtd_input
@Tomalak 您可以在 XHTML 中使用方括号字符“[”和“]”,请参阅 http://www.w3.org/TR/xhtml1/dtds.html#dtdentry_xhtml1-transitional.dtd_input
So this means that a name can contain many different characters legally within XHTML, although it doesn't make much sense to use slashes or brackets. PHP supports the use of array notation in form names, so you could be missing a trick if you don't use array notation in some instances.
所以这意味着一个名称可以在 XHTML 中合法地包含许多不同的字符,尽管使用斜杠或括号没有多大意义。PHP 支持在表单名称中使用数组表示法,因此如果在某些情况下不使用数组表示法,您可能会错过一个技巧。
回答by FDisk
var data = $(form).serialize();
$.post('post.php', '&'+data);
回答by tvanfosson
You may need to change your PHP as @Tomalak suggests, but you will also need to change your javascript. To reference a named element use the #name selector:
您可能需要按照@Tomalak 的建议更改您的 PHP,但您还需要更改您的 javascript。要引用命名元素,请使用 #name 选择器:
var selectedbooks = $('form#book_form').serialize();;
回答by tvanfosson
Thanks Tomalak.
谢谢托马拉克。
In the PHP file, I am using the following code now:
在 PHP 文件中,我现在使用以下代码:
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
echo "<tr>";
echo "<td bgcolor='#FFFFFF'><input id='$book_id' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>";
echo "<td bgcolor='#FFFFFF'>$book_name</td>";
echo "</tr>";
} // while
**The book_id is unique.
** book_id 是唯一的。
Using tvanfosson solution, now i am able to get array of input value
使用 tvanfosson 解决方案,现在我可以获得输入值数组
var selectedBooks = $('form#book_form').serialize(); alert (selectedBooks);
var selectedBooks = $('form#book_form').serialize(); 警报(选定的书籍);
From the alert message box, I get ==> bookArray%5B%5D=T2.05&bookArray%5B%5D=T2.81
从警报消息框中,我得到 ==> bookArray%5B%5D=T2.05&bookArray%5B%5D=T2.81
Now, when I sent the serialize input value to PHP file using JQuery
现在,当我使用 JQuery 将序列化输入值发送到 PHP 文件时
var selectedBooks = $('form#book_form').serialize();
alert (selectedBooks);
var url = 'saveBookList.php';
// Send to server using JQuery
$.post(url, {bookArray: selectedBooks}, function(responseData) {
$("#save-result").text(responseData);
});
Inside saveBookList.php to process the serialize form, i got this error "Invalid argument supplied for foreach()".
在 saveBookList.php 处理序列化表单时,我收到此错误“为 foreach() 提供的参数无效”。
Inside saveBookList.php,
在 saveBookList.php 中,
// If you have selected from list box.
if(isset($_POST['bookArray'])) {
// Get array or bookID selected by user
$selectedBookId = $_POST['bookArray'];
echo $selectedBookId;
foreach($selectedBookId as $selectListItem) {
echo "You sent this -->" . $selectListItem . "\n";
}
}
The PHP code above works fine if i am sending using Prototype.
如果我使用 Prototype 发送,上面的 PHP 代码工作正常。
For Prototype when i do echo $selectedBookId;
对于原型,当我做 echo $selectedBookId;
I got Array.
我得到了阵列。
For JQuery, when i do echo $selectedBookId;
对于 JQuery,当我做 echo $selectedBookId;
I got ==> bookArray%5B%5D=T4.11&bookArray%5B%5D=T4.38
我得到 ==> bookArray%5B%5D=T4.11&bookArray%5B%5D=T4.38
My question, does jQuery support array value for post method?
我的问题,jQuery 是否支持 post 方法的数组值?

