2014-04-09 109 views
1

我嘗試使用jQuery將多個值發佈到PHP頁面,然後將該值用作單個值。具有多個值的jQuery序列化函數

我先從jQuery的站點代碼:

<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頁面,然後用獨特的價值觀,像這樣:

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

回答

2

更改multiplemultiple[]在表單中。這會將您的值提交爲多個[] =第一個值,多個[] =第二個值等等。

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. 
} 
+0

TNX了很多!最好的祝福 ! – Pavlen

+0

不客氣@Pavlen。 :) –

0

你必須張貼的形式使用AJAX test.php的。試試這個 -

$("form").on('submit', function(ev){ 

    ev.preventDefault(); 
    var form = $(this); 
    var action = 'test.php'; 
    var data = $(this).serialize(); 

    $.post(action, data) 
    .done(function(response){ 

     if(response.success == false) 
     { 
      // If failed 
     } 
     else 
     { 
      // If successfully submitted 
     } 
    }); 
}); 

而在另一邊(test.php的),你會得到你的多個值的一個這樣的數組,

$multiple1 = $_POST['multiple']['0']; 
$multiple2 = $_POST['multiple']['1'];