1

I have created one string array in jquery of name array[] and pushed values to it.

How can I send this array in query string?

For example window.location.href('ViewData?array');

And how can I get back the array data from query string in jquery itself ? Please advice?

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Raju S Nair
  • 333
  • 2
  • 5
  • 17
  • 1
    The query string, well is a string :), so you convert your array to some kind of string format, like xml, but not xml because will be come huge, and then you read it from the other side and convert it to array again. – Aristos Aug 22 '14 at 06:39
  • yup, converting to sting is one option. But it would be safer when send as array as received as array in jquery since we are revealing the key of key value pair – Raju S Nair Aug 22 '14 at 06:43

2 Answers2

7

This is very easy to achieve with jQuery as it has a helper function called param().

var myData = {
   name: "John Doe",
   age: 23,
   children: [{
      name: "Jane Doe",
      age: 13,
      children: []
      },
      {
      name: "John Doe Jr.",
      age: 16,
      children: []
      }
   ],
}
var p = $.param(myData)

The results:

"name=John+Doe&age=23&children%5B0%5D%5Bname%5D=Jane+Doe&children%5B0%5D%5Bage%5D=13&children%5B1%5D%5Bname%5D=John+Doe+Jr.&children%5B1%5D%5Bage%5D=16"

You can use it like so:

window.location = "/MyController/MyAction?" + p;

As for getting parameters from query strings, please refer to the following question: How can I get query string values in JavaScript?


Another thing you can do is use an ajax call, this way you don't have to serialize the data yourself as it is done for you automatically.

$.ajax({
  url: "/MyController/MyAction",
  data: myData,
  dataType: "json",
  type: "POST",
  success: function(data){
    //'data' is your response data from the Action in form of a javascript object
  }
})
Community
  • 1
  • 1
ngergo6
  • 267
  • 1
  • 11
1

I think this is what you are looking for. Let me know if I get it wrong. I copied $.parseParams from this link. You can also see working code here

(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g;  // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
    var params = {}, e;
    while ( e = re.exec(query) ) { 
        var k = decode( e[1] ), v = decode( e[2] );
        if (k.substring(k.length - 2) === '[]') {
            k = k.substring(0, k.length - 2);
            (params[k] || (params[k] = [])).push(v);
        }
        else params[k] = v;
    }
    return params;
};
})(jQuery);

var s=["abc", "xyz", "123"];
var queryString=$.param({a:s});
console.log("object to query string: ", queryString);
console.log("query string to object: ", $.parseParams(queryString));
Sanjay Sahani
  • 565
  • 4
  • 14