从url获取值json值

时间:2013-04-16 12:29:20

标签: javascript json

我查看了各种帖子,现在使用函数从url中检索值但无法删除%20个字符。发送的数据是json,这是在url中发送它的代码:

'<a href="' + url +"?id="+ json_data[i].product_id + 
...
"&description="+ json_data[i].description + '"> //includes white spaces

在另一页上我有:

function getUrlVars()
{
 var vars = [], hash;
 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 for(var i = 0; i < hashes.length; i++)
 {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
 }
return vars;
}

var selectedData=getUrlVars();
document.write(selectedData.description); 

1 个答案:

答案 0 :(得分:0)

使用encodeURIComponentdecodeURIComponent功能:

"&description="+ encodeURIComponent(json_data[i].description) + '"

decoreURIComponent(hash[1]);

如果说明中有&符号,这将占用空间,但也会使事情有效。
例如:

> hash
["clean", "Machine%20washable%2030%20degrees%20reduced%20spin"]
> decodeURIComponent(hash[1]);
"Machine washable 30 degrees reduced spin"