Reputation: 1413
how to process an array as get str to url?
I want to send an array to my PHP page as get prometers , don't care about how long the get str , it is only use in my site admin side. what should I process the array to a sting ,when in PHP site I can re process it back to array.
<script type="text/javascript">
function arr_to_get_str(arr){
// how should I make a get string from an array?
// what format should this str shows
return str;
}
var arr=[
[
key :'products_id',
operator: '>',
value : '20'
],
[
key :'products_name',
operator: 'like',
value : '%hello world%'
]
];
var base_uri='http://localhost/test.php';
var url= base_uri + '?'+ arr_to_get_str(str);
location.href = url;
</script>
Upvotes: 2
Views: 198
Reputation: 8309
Make a JSON string of your array, & encode it into Base64 with window.btoa
var jsonString = JSON.stringify(array); var encString = window.btoa(jsonString); // supports all except- ie- below version 10
Send it in request parameter
var url= base_uri + '?request='+ arr_to_get_str(arr);
In .php file, get the string & decode it to Array or Object
$requestJsonStr = base64_decode($_GET['request']); //EITHER make an Array from the JSON-String $requestArray = json_decode($requestJsonStr, TRUE); //OR make an Object from the JSON-String $requestArray = json_decode($requestJsonStr, FALSE);
Upvotes: 1
Reputation: 1149
Rather use encodeURIComponent
:
var url= base_uri + '?q='encodeURIComponent(JSON.stringify(arr));
then php is:
$arrParameters = isset($_GET['q']) ? json_decode(url_decode(($_GET['q'])) : array();
This will get you the parameters or return an empty array if there are none. Not the best practice, but if it an "hackish" admin system, go for it
Upvotes: 1
Reputation: 40639
Try this,
function arr_to_get_str(arr){
var str='';
var strarr= new Array();
for(var i=0;i<arr.length;i++)
{
strarr.push(arr[i]['key']+' '+arr[i]['operator']+' '+arr[i]['value']);
}
str=strarr.join(' AND ');
return str;
}
var arr=[
{
key :'products_id',
operator: '>',
value : '20'
},
{
key :'products_name',
operator: 'like',
value : '%hello world%'
}
];
var base_uri='http://localhost/test.php';
var url= base_uri + '?q='+arr_to_get_str(arr);
alert(url);
//http://localhost/test.php?q=products_id > 20 AND products_name like %hello world%
Fiddle http://jsfiddle.net/vSuDZ/
Upvotes: 0
Reputation: 522402
For a complex data structure, the best encoding would be JSON. JSON is pretty inefficient in a URL though, as a lot of characters need to be inefficiently URL escaped. This may be a good use case for Rison. You can find a Javascript implementation on the site and a PHP implementation here.
Upvotes: 1