post associative array using jquery ajax

2020-07-29 00:29发布

I am creating form using cakephp form. It is creating form something like this:

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

It is working fine when submitting form in normal form and getting data something like this:

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

But when I submit same form using jQuery $.ajax() function and posting data with serialize() function. I am getting data something like this on server side.

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
)

How can I get form data in form of associate arrays when usign jQuery $.ajax() function ?

EDIT:

$('#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();
});

Thanks

5条回答
地球回转人心会变
2楼-- · 2020-07-29 00:51

serializeArray(); is what you are looking for

查看更多
ゆ 、 Hurt°
3楼-- · 2020-07-29 00:55

You can use .serializeArray() and then manually encode the values:

var values = form.serializeArray();
for (var i = 0; i < values.length; i++)
    values[i] = encodeURIComponent(values[i].value);
values = values.join('&');
查看更多
别忘想泡老子
4楼-- · 2020-07-29 00:57

No need to user Low-Level ajax, use $.post shorthand instead.

Try this:

$(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   
      });

   });  

});

You asked for POST ASSOC ARRAY Using jquery, so you'll get that,

In your php script:

<?php

print_r($_POST); //will print what you want
查看更多
啃猪蹄的小仙女
5楼-- · 2020-07-29 01:04

One of possible solutions is to parse key strings on server side and build associated array in PHP...

查看更多
来,给爷笑一个
6楼-- · 2020-07-29 01:07

I think jQuery.param is what you're looking for.

查看更多
登录 后发表回答