开发者

Is there a javascript equivalent of php's urldecode or html_entity_decode()?

I've got an associative array in php that I want to stick into a hidden form input so that I can later get the values in javascript. Because of quoting issues, I need to urlencode the json, or htmlentity it. Once I have the object in javascript, though, what's the easiest way to get it back to plain ol' json?

OR is there a better way to approach this issu开发者_开发知识库e? AJAX seems like overkill here -- I'd rather pre-populate the data on the page, rather than setting up multiple requests. I suppose I could write the php object to the page inside a php-generated script tag, but that seems a bit messy, and I'm not certain that [scripts] will be parsed in every possible situation where this might be used.


If you stick the data within a field you could use decodeURIComponent to decode the value. Example:

decodeURIComponent("%5b'hello'%2c%20'world'%5d"); // ['hello', 'world']

Another approach might be to embed the JSON object in a <script> element in the PHP output. You could even go as far as to make the JSON object an argument to a function that stores it away somewhere.

<script>setupData(<?= toJSON(['hello', 'world']) ?>)</script>

When the page loads the setupData would be called with the literal ['hello', 'world'].


Oh. I guess I should have tested first. I'm using dojo, and this Just Works:

PHP:

$arr = array('nyc'=>'big apple', 'boss'=>'big banana', 'lion'=>'big cat');
$json = htmlentities(json_encode($arr));
echo '<input type="hidden" id="myHidden" value="' . $json . '" />';

Javascript:

var raw = dojo.byId('myHidden').value;
var arr = dojo.fromJson(raw);
for (var i in arr) {
    console.log(i + " => " + arr[i]);
}

[sheepish grin]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜