android webview内嵌网页js解析json 并根据json数据生成表单以及radio的样式问题
在开发android app时,常常碰到新闻客户端的开发,新闻客户端的新闻详细页面很可能是一个html,android端需要用webview来展示,但是如果需要webview与android端相互调用,都会用到js与android端的相互调用,但是如果要传递一个json数据到webview,调用网页的js来解析json获取数据来调用相关的方法,那就需要js解析json。
js解析json,我用的是eval函数。
function initToupiaoTest() {
//date是手机端传递过来的对象,get获取一个json
var str = eval("("+datas.getTestJson().toString()+")");
var main = str['main'],questions = str['questions'];
for(var i=0;i< questions.length;i++)
{
console.log('hello : ******测试**** >>>>>>>>> = '+questions[i]._id);
for(var j=0;j<questions[i].answers.length;j++)
{
//alert(questions[i].answers[j].title)//拿到answers的元素
console.log('hello : ******测试**** >>>>>>>>> = '+questions[i].answers[j].title);
}
}
}
//模拟数据
var str = '{"main":{"_id":"xxx","catid":"1707","description":"","exit_content":"","exit_title":"","exit_url":"","status":10,"sub_title":"","title":"list\u6d4b\u8bd5","checkresult":0},"questions":[{"_id":"xxx","title":"Q2\uff1a","type":"radio","is_required":"1","answers":[{"_id":"xxx","title":"A.","hits":15},{"_id":"xxx","title":"B.","hits":11}]},{"_id":"xxx","title":"Q1\uff1a","type":"radio","is_required":"1","answers":[{"_id":"xxx","hits":12,"title":"titleA."},{"_id":"xxx","hits":17,"title":"titleB."}]}]}';
//生成表单
<div id="toupiao">
<h4>
<span></span>
<P style="color:#ffffff;background-image: url(bluel.png);font-family: '微软雅黑';" id="q_title">您觉得这次改版如何</p>
<span></span>
</h4>
<form >
<div id="qlist">
<!-- 这里是生成表单内容-->
</div>
<div style="width:100%;text-align:center;"><input type="button" name="aa" style="color:#ffffff;background-image: url(bluel.png);width:80%;line-height:38px;height:38px;font-family: '微软雅黑';" value="显示投票结果" onClick="hi()"/></div>
</form>
</div>
//js代码
var main = str['main'],questions = str['questions'],htmlArr = new Array();
for(var i=0;i< questions.length;i++)
{
//alert(questions[i]._id)//拿到questions的元素
htmlArr.push('<p style="font-weight:bold;" id="'+questions[i]._id+'">'+questions[i].title+'</p>');
for(var j=0;j<questions[i].answers.length;j++)
{
//alert(questions[i].answers[j].title)//拿到answers的元素
htmlArr.push('<label class="input"><input type="radio" name="aa" id="'+questions[i]._id+'"> '+questions[i].answers[j].title+'</label><br>');
}
}
document.getElementById('qlist').innerHTML = htmlArr.join('');
如果展示的radio样式有问题,在webview中展示为一条下划线,那么在代码中注释掉如下代码
/*mWebview.getSettings().setLayoutAlgorithm(
WebSettings.LayoutAlgorithm.SINGLE_COLUMN);*/