AngularJS - How to send multidimensional $http.get() data

时间秒杀一切 提交于 2019-12-12 20:27:06

问题


So I have a JSON array that looks something like this:

var myData = {
    foo : {
        biz : 'baz',
        fig : 'tree'
    }
}

This could be typed into the address bar like:

http://www.mysite.com/index?foo[biz]=baz&foo[fig]=tree

And this will work as expected.

The problem is that when I supply this myData object to AngularJS's $http service like:

$http.get('http://www.mysite.com', {
    data : myData
});

It escapes the query string and doesn't appear to even be the right format even if it weren't esaped in the weird way it is. It looks something like:

url?foo=%7B%22biz%22%3A%22baz%22%2C%22fig%22%3A%22tree%22%7D

How can I make this work?


回答1:


This is actually in the right format. Assuming your back-end is PHP, when you do $_GET['foo'] you will get %7B%22biz%22%3A%22baz%22%2C%22fig%22%3A%22tree%22%7D. The strange characters you see are because Angular is url encoding the string for you. This has to be done before transmitting the data. If you type it out as foo[biz]=baz&foo[fig]=tree in your browser, the browser usually urlencodes it automatically.

After urldecoding and json_decoding this, you will get the data you expect.

$foo = json_decode(urldecode($input), true);

Array
(
    [biz] => baz
    [fig] => tree
)

You can then access these as $foo['biz'] and $foo['fig']

Demo



来源:https://stackoverflow.com/questions/15192255/angularjs-how-to-send-multidimensional-http-get-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!