开发者

json_encode combined with $_GET (PHP & Javascript)

I need to pass a JSON array into a webpage URL so I do

$url = 'page.php?id=' . json_encode($array);

which becames

$url = 'pages.php?id=["1", "2", "3"]';
开发者_运维知识库

And then, inside page.php which is basically Javascript code i do

var foo = <?php $_GET['id']; ?>

But foo instead of being an array like ["1", "2", "3"] it's only [.

Why is this?

Also, is it better to do: url.php?id=value or url.php?id="value"??


You forgot to urlencode() it.

$url = 'page.php?id=' . urlencode(json_encode($array));

And don't forget to json_decode() it when it gets back.


Out of curiosity do you have to pass it as a json_encoded string?

Perhaps you could pass it as an array

page.php?id[]=1&id[]=2&id[]=3 

then your page.php code would look like this:

echo json_encode($_GET['id']);

I would also check for bad data using a white list approach if your passing in page ids.

$safe = array('1','2','3');
$id = $_GET['id'];
foreach($id as $value){
 if(!in_array($value, $safe)){
    echo "Sry, data not valid";
    exit;
 }
}
echo json_encode($id);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜