jQuery序列化具有多个值的函数 [英] jQuery serialize function with multiple values

查看:78
本文介绍了jQuery序列化具有多个值的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jQuery将多个值发布到PHP页面,然后将该值用作单个值.

I try to use jQuery to post multiple values to PHP page, and then use that values as a single values.

我从Jquery网站的代码开始:

I start with code from Jquery site :

  <form ><br>
  <select name="multiple" multiple="multiple">
   <option selected="selected">Multiple</option>
   <option>Multiple2</option>
   <option selected="selected">Multiple3</option>
  </select>

  <br>

 <br>

 </form>

 <p><tt id="results"></tt></p>

  <script>
     function showValues() {
     var str = $( "form" ).serialize();
     $( "#results" ).text( str );
                            }
    $( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
    $( "select" ).on( "change", showValues );
   showValues();
    </script>

结果是:multiple=Multiple&multiple=Multiple2,这很好.

现在,mycproblem是如何将这些值发布到test.php页,然后使用唯一值,例如:

Now mycproblem is how to post these values to test.php page, and then to use unique values, like this :

$multiple=[first value]
$multiple2=[second value]
etc...

推荐答案

将表单中的multiple更改为multiple[].这会将您的值提交为multiple [] = 1st值,multiple [] = 2nd值等.

Change your multiple to multiple[] in your form. This will submit your values as multiple[]=1st value, multiple[]=2nd value and more.

jQuery,

$('form').on('submit', function(e)
{
  e.preventDefault();
  formData=$('form').serialize();
    $.ajax(
    {
        type: "POST",
        url: "test.php",
        data: formData,
        success: function(data)
        {
            alert("Form submitted");
        },
        error: function()
        {
            alert("Error in form submission");
        }
    });
});

在PHP端,

$multiple=$_POST['multiple']; // Get the array input

现在分别处理这些值,

foreach($multiple as $key => $value)
{
echo "value number $key is $value"; // This will print as value number 0 is 1st value, value number 1 is 2nd value and more.
}

这篇关于jQuery序列化具有多个值的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆