开发者

Pass multi-dimensional array in ajax request with jQuery

how to send two dimensional array in Url for ajax

likes:

MultiArray[0][1]="..."
MultiArray[0][2]="..."
.
.
MultiArray[n][1]="..."
MultiArray[n][2]="..."

code from ajax(ja开发者_高级运维vascript) to php like

<a href="test.php?t=MultiArray">...</a>

please help


You can't send an object in the URL, you can only send string values.

You can create a value that represent a jagged array (which is what you have as Javascript doesn't have multi-dimensional arrays), like:

test.php?t=[[1,2,3],[4,5,6],[7,8,9]]

This would of course have to be parsed on the server side.

You might want to look at the JSON data format. IIRC jQuery can create JSON format, or there is at least a plugin for that. There ought to be some library in PHP that can parse the format.


There are many ways you can solve this.

  • Encode your data on the client side in your custom data structure and code it using base64 and send it as one parameter
  • If there are limited (like 10) rows and columns you could just serialize to your liking: ?r1c1=0&r2c2=1 etc and decode in your php script.

I would suggest the first alternative though.


Here is a real Ajax request in jQuery. Look at the data parameter for $.ajax.

should('test paramterized multidimensional object', function() {
   var mDimArray = [];
    mDimArray[0] = [];
    mDimArray[1] = [];

    mDimArray[0][0] = 'data 0';
    mDimArray[0][1] = 'data 1';
    mDimArray[1][0] = 'data 2';
    mDimArray[1][1] = 'data 3';

    jQuery.ajax({
        url:        'test.php'
        ,data:      { mDims: mDimArray }
        ,dataType:  'json'
        ,success:   function(data) {
            if (data.status === "success") {
                ok(true, "Rx Json");                
            }
        }
    });

});

Here is what the parameters in the request look like:

mDims[0][]  data 0
mDims[0][]  data 1
mDims[1][]  data 2
mDims[1][]  data 3

The query string:

?mDims%5B0%5D%5B%5D=data+0&mDims%5B0%5D%5B%5D=data+1&mDims%5B1%5D%5B%5D=data+2&mDims%5B1%5D%5B%5D=data+3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜