ajax的serialize()方法

时间:2021-09-08 16:04:47

自己看吧,超级简单,就不用挨个获取表单名称和值对装在Json里往php传了,直接传个form就可以。

【HTML】

<form method="post" id="form1">
  Order: <input type="text" name="order" value="">
  Name: <input type="text" name="name" value="">
  Old: <input type="text" name="old" value="">
  Gender: <input type="radio" name="gender" value="female">男
      <input type="radio" name="gender" value="male">女
  Choose: <select name="choose">
        <option value="c1">c1</option>
        <option value="c2">c2</option>
        <option value="c3">c3</option>
      </select>
  <!-- 什么复选框,hidden的表单啊,我都没往上写,都是可以的。-->
</form>
<button>触发</button>
result: <p></p>

【jQuery】

$("button").click(function(){
  $.ajax({
    url:'2.php',
    type:'POST',
    data:$("#form1").serialize(),
    success:function(response){
      $("p").text(response);
    }
  });
});

【PHP】

$order=$_POST['order'];  //可以用$_POST获取到input表单,name所对应的值
$name=$_POST['name'];
$old=$_POST['old'];
$gender=$_POST['gender'];
$choose=$_POST['choose']; echo "Order: ".$order." ";
echo "Name: ".$name." ";
echo "Old: ".$old." ";
echo "Gender: ".$gender." ";
echo "Choose: ".$choose." ";

输出结果:Order: 1 Name: 1 Old: 1 Gender: female Choose: c3