2

如何处理数组作为获取 str 到 url?
我想将一个数组作为 get prometers 发送到我的 PHP 页面,不关心 get str 多长时间,它只在我的站点管理端使用。我应该如何将数组处理成一个字符串,当在 PHP 站点中我可以将它重新处理回数组时。

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

4 回答 4

1

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.

于 2013-05-27T11:22:41.220 回答
1

而是使用encodeURIComponent

var url= base_uri + '?q='encodeURIComponent(JSON.stringify(arr)); 

那么php是:

$arrParameters = isset($_GET['q']) ? json_decode(url_decode(($_GET['q'])) : array();

如果没有,这将为您获取参数或返回一个空数组。不是最佳实践,但如果它是一个“hackish”管理系统,那就去吧

于 2013-05-27T11:25:18.007 回答
1
  1. 为您的数组创建一个 JSON 字符串,并使用window.btoa将其编码为 Base64

    var jsonString = JSON.stringify(array);
    var encString  = window.btoa(jsonString); 
    // supports all except- ie- below version 10
    
  2. 在请求参数中发送

    var url= base_uri + '?request='+ arr_to_get_str(arr);

  3. .php文件中,获取字符串并将其解码为数组或对象

    $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);
    
于 2013-05-27T14:28:54.690 回答
0

尝试这个,

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%

小提琴http://jsfiddle.net/vSuDZ/

于 2013-05-27T11:22:24.327 回答