簡體   English   中英

使用jQuery Ajax發布關聯數組

[英]post associative array using jquery ajax

我正在使用cakephp表單創建表單。 它正在創建這樣的形式:

<form name='license' action='/some/action' action='POST'>

  <input type="text" id="license0Number" name="data[license][0][number]">
  <input type="text" id="license0Year" name="data[license][0][year]">

  <input type="text" id="license1Number" name="data[license][1][number]">
  <input type="text" id="license1Year" name="data[license][1][year]">

</form>

當以正常形式提交表單並獲取數據時,它工作正常:

$data = array( 'license' => array( '0' => array( 'number'=>'123', 'year'=>'2000' ),
                                   '1' => array( 'number'=>'321', 'year'=>'2003' )
                                 );

但是,當我使用jQuery $.ajax()函數提交相同的表單並使用serialize()函數發布數據時。 我正在服務器端獲取類似這樣的數據。

Array
(
[data%5Blicense%5D%5B0%5D%5Bnumber%5D] => 123
[data%5Blicense%5D%5B0%5D%5Byear%5D] => 2000
[data%5Blicense%5D%5B1%5D%5Bnumber%5D] => 321
[data%5Blicense%5D%5B1%5D%5Byear%5D] => 2003
)

使用usign jQuery $ .ajax()函數時,如何獲取關聯數組形式的表單數據?

編輯:

$('#license_form').live( 'submit', function( event ) {

  var action = '/some/action';
  var data = $(this).serialize();

  $.ajax({

     type: "POST",
     url: action,
     data: data, // form data
     success: function( result ) { alert( result ); },
     error: function() { alert('error'); }
  });

   event.preventDefault();
});

謝謝

無需使用低級Ajax,請改用$ .post速記。

嘗試這個:

$(function(){

  $("#submit").click(function(){
     //Since you're talking about POST
     $.post('path_to_php_script.php', {

       "license0Number" : $("#license0Number").val(),
       "license0Year"   : $("#license0Year").val(),
       "license1Number" : $("#license1Number").val(),
       "license1Year"   : $("#license1Year").val()


      }, function(respond){

          //Respond from PHP
          //Maybe replace some div with the server respond?
          $("#some_div").html(respond); //optional   
      });

   });  

});

您使用jquery詢問了POST ASSOC ARRAY,所以您會明白這一點,

在您的PHP腳本中:

<?php

print_r($_POST); //will print what you want

您可以使用.serializeArray() ,然后手動編碼值:

var values = form.serializeArray();
for (var i = 0; i < values.length; i++)
    values[i] = encodeURIComponent(values[i].value);
values = values.join('&');

一種可能的解決方案是在服務器端解析鍵字符串並在PHP中構建關聯的數組...

我認為jQuery.param是您想要的。

serializeArray(); 是您要尋找的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM