如果input元素是一个数组,如何使用JQuery发送序列化表单数据

时间:2021-11-10 21:19:20

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时,它工作得很好。

14 个解决方案

#1


22  

easy: serialize().replace(/%5B%5D/g, '[]')

easy:serialize()。replace(/%5B%5D / g,'[]')

#2


9  

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

#3


2  

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

      }
});

#4


1  

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() ) );" ...>
...

#5


1  

@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支持在表单名称中使用数组表示法,因此如果在某些情况下不使用数组表示法,则可能会丢失技巧。

#6


1  

jQuery 1.4

var myform = $("book_form").serialize();

decodeURIComponent(myform);

#7


1  

work correctly jquery =>

正确工作jquery =>

var data = $('form').serialize();
            $.post(baseUrl+'/ajax.php',
                    {action:'saveData',data:data},
                    function( data ) {
                        alert(data);
                    });

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://*.com/questions/1792603

你可以用阵列数据做任何你想做的事,感谢Aridane https://*.com/questions/1792603

#8


0  

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:

您可能需要更改PHP,因为@Tomalak建议,但您还需要更改您的JavaScript。要引用命名元素,请使用#name选择器:

var selectedbooks = $('form#book_form').serialize();;

#9


0  

Problem solved! Here is what i did.

问题解决了!这就是我做的。

Inside PHP file to create rows of dynamic checkboxes,

在PHP文件内部创建动态复选框行,

  while ($row = mysqli_fetch_assoc($result))
  {
   extract($row);
   echo "<tr>";
   echo "<td bgcolor='#FFFFFF'><input name='books' type='checkbox' value='$book_id' />$book_id</td>";
   echo "<td bgcolor='#FFFFFF'>$book_name</td>";
   echo "</tr>";
  } // while

I do not use JQuery $.post method anymore. I changed my code to the following

我不再使用JQuery $ .post方法了。我将代码更改为以下内容

    var my_query_str = '';

$("input[@type='checkbox'][@name='books']").each(
  function()
  {
    if(this.checked)
    {
           my_query_str += "&bookArray[]=" + this.value;
    }
  });


$.ajax(
{
    type: "POST",
    url: "saveBookList.php",
    data: "dummy_data=a" + my_query_str,
    success:
        function(responseData)
        {
            $("#save-result").empty().append(responseData);
        },
    error:
        function()
        {
            $("#save-result").append("An error occured during processing");
        }
});

Now, inside saveBookList.php page, value of $_POST['bookArray'] is an Array. Yey! Yey!

现在,在saveBookList.php页面中,$ _POST ['bookArray']的值是一个数组。 Yey! Yey!

I do hope and wish the $.post method of JQuery can support array data type as Prototype does. :)

我希望并希望JQuery的$ .post方法可以像Prototype那样支持数组数据类型。 :)

#10


0  

var data = $(form).serialize();
$.post('post.php', '&'+data);

#11


0  

it's not a problem with jQuery Post, it's with serialize you can do this:

它不是jQuery Post的问题,它是序列化你可以这样做:

    var my_query_str = ''; 
    $("input[@type='checkbox'][@name='books']").each( function() { 
       if(this.checked) { my_query_str += "&bookArray[]=" + this.value; } 
    }); 
   jQuery.post(
      "saveBookList.php",
      "dummy_data=a" + my_query_str ,
       function(responseData){   
          $("#save-result").empty().append(responseData); 
       }, 
       error: function() { 
            $("#save-result").append("An error occured during processing"); 
       }
   }); 

but all you really have to do is replace '[' & ']' back to themselves after serializing them. because serialize(); changed them to their htmlencoded value!

但是你真正需要做的就是在序列化之后将'['&']'替换回自己。因为serialize();将它们改为htmlencoded值!

#12


0  

If you have to post that array only and not other input fields, this is a clean and quick solution:

如果您只需要发布该数组而不是其他输入字段,这是一个干净,快速的解决方案:

var selectedbooks = $('book_form input[name^="bookArray["]').serialize();
alert (selectedbooks); 

Explaination:

The selector ^= selects all elements with a name attribute value starting with 'bookArray', the open square bracket '[' makes sure the element is the array we want to serialize and not just a variable starting with the string 'bookArray'.

选择器^ =选择名称属性值以'bookArray'开头的所有元素,开放方括号'['确保元素是我们想要序列化的数组,而不仅仅是以字符串'bookArray'开头的变量。

#13


0  

You have to replace left square brackets and right square brackets with this:

您必须将左方括号和右方括号替换为:

data: $(this).serialize().replace(/%5B/g, '[').replace(/%5D/g, ']'),

#14


0  

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();提醒(selectedBooks);

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,

// 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;

对于Prototype,当我做回声$ selectedBookId;

I got Array.

我有阵。

For JQuery, when i do echo $selectedBookId;

对于JQuery,当我做回声$ 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方法的数组值?

#1


22  

easy: serialize().replace(/%5B%5D/g, '[]')

easy:serialize()。replace(/%5B%5D / g,'[]')

#2


9  

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

#3


2  

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

      }
});

#4


1  

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() ) );" ...>
...

#5


1  

@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支持在表单名称中使用数组表示法,因此如果在某些情况下不使用数组表示法,则可能会丢失技巧。

#6


1  

jQuery 1.4

var myform = $("book_form").serialize();

decodeURIComponent(myform);

#7


1  

work correctly jquery =>

正确工作jquery =>

var data = $('form').serialize();
            $.post(baseUrl+'/ajax.php',
                    {action:'saveData',data:data},
                    function( data ) {
                        alert(data);
                    });

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://*.com/questions/1792603

你可以用阵列数据做任何你想做的事,感谢Aridane https://*.com/questions/1792603

#8


0  

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:

您可能需要更改PHP,因为@Tomalak建议,但您还需要更改您的JavaScript。要引用命名元素,请使用#name选择器:

var selectedbooks = $('form#book_form').serialize();;

#9


0  

Problem solved! Here is what i did.

问题解决了!这就是我做的。

Inside PHP file to create rows of dynamic checkboxes,

在PHP文件内部创建动态复选框行,

  while ($row = mysqli_fetch_assoc($result))
  {
   extract($row);
   echo "<tr>";
   echo "<td bgcolor='#FFFFFF'><input name='books' type='checkbox' value='$book_id' />$book_id</td>";
   echo "<td bgcolor='#FFFFFF'>$book_name</td>";
   echo "</tr>";
  } // while

I do not use JQuery $.post method anymore. I changed my code to the following

我不再使用JQuery $ .post方法了。我将代码更改为以下内容

    var my_query_str = '';

$("input[@type='checkbox'][@name='books']").each(
  function()
  {
    if(this.checked)
    {
           my_query_str += "&bookArray[]=" + this.value;
    }
  });


$.ajax(
{
    type: "POST",
    url: "saveBookList.php",
    data: "dummy_data=a" + my_query_str,
    success:
        function(responseData)
        {
            $("#save-result").empty().append(responseData);
        },
    error:
        function()
        {
            $("#save-result").append("An error occured during processing");
        }
});

Now, inside saveBookList.php page, value of $_POST['bookArray'] is an Array. Yey! Yey!

现在,在saveBookList.php页面中,$ _POST ['bookArray']的值是一个数组。 Yey! Yey!

I do hope and wish the $.post method of JQuery can support array data type as Prototype does. :)

我希望并希望JQuery的$ .post方法可以像Prototype那样支持数组数据类型。 :)

#10


0  

var data = $(form).serialize();
$.post('post.php', '&'+data);

#11


0  

it's not a problem with jQuery Post, it's with serialize you can do this:

它不是jQuery Post的问题,它是序列化你可以这样做:

    var my_query_str = ''; 
    $("input[@type='checkbox'][@name='books']").each( function() { 
       if(this.checked) { my_query_str += "&bookArray[]=" + this.value; } 
    }); 
   jQuery.post(
      "saveBookList.php",
      "dummy_data=a" + my_query_str ,
       function(responseData){   
          $("#save-result").empty().append(responseData); 
       }, 
       error: function() { 
            $("#save-result").append("An error occured during processing"); 
       }
   }); 

but all you really have to do is replace '[' & ']' back to themselves after serializing them. because serialize(); changed them to their htmlencoded value!

但是你真正需要做的就是在序列化之后将'['&']'替换回自己。因为serialize();将它们改为htmlencoded值!

#12


0  

If you have to post that array only and not other input fields, this is a clean and quick solution:

如果您只需要发布该数组而不是其他输入字段,这是一个干净,快速的解决方案:

var selectedbooks = $('book_form input[name^="bookArray["]').serialize();
alert (selectedbooks); 

Explaination:

The selector ^= selects all elements with a name attribute value starting with 'bookArray', the open square bracket '[' makes sure the element is the array we want to serialize and not just a variable starting with the string 'bookArray'.

选择器^ =选择名称属性值以'bookArray'开头的所有元素,开放方括号'['确保元素是我们想要序列化的数组,而不仅仅是以字符串'bookArray'开头的变量。

#13


0  

You have to replace left square brackets and right square brackets with this:

您必须将左方括号和右方括号替换为:

data: $(this).serialize().replace(/%5B/g, '[').replace(/%5D/g, ']'),

#14


0  

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();提醒(selectedBooks);

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,

// 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;

对于Prototype,当我做回声$ selectedBookId;

I got Array.

我有阵。

For JQuery, when i do echo $selectedBookId;

对于JQuery,当我做回声$ 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方法的数组值?