使用json把php数据传给js处理
先创建下面的两个文件,并将代码拷贝进去,然后打开json.html文件:
json.html文件:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>json测试</title> <style type="text/css"> body { text-align:center; } .image { width: 240px; border:2px solid #EEE; margin-top: 30px; } </style> </head> <body> <div> <img src="#" class="image"> </div> <div> <img src="#" class="image"> </div> </body> <script type="text/javascript" language="javascript"> function loadjson( _json ) { if( _json ) { var imgs = document.getElementsByClassName('image'); for(var i=0; i < _json.length && i < imgs.length; i++) { //console.log(_json[i].src); //console.log(_json[i].title); //console.log(_json[i].alt); imgs[i].src = _json[i].src; imgs[i].title = _json[i].title; imgs[i].alt = _json[i].alt; } } } function getjson() { var xhr = new XMLHttpRequest(); xhr.open('GET', 'json.php', true); xhr.onreadystatechange = function() { if(xhr.readyState == 4) { var resText = xhr.responseText; //console.log(resText); var jsonstr = eval(resText); loadjson(jsonstr); } }; xhr.send(null); } getjson(); </script> </html>
json.php文件:
<?php $arr = array( array( 'src' => 'https://p.ssl.qhimg.com/t01d1f1a2ae31e3c3e4.png', 'title' => '360搜索,SO靠谱', 'alt' => '360搜索' ), array( 'src' => 'https://www.baidu.com/img/bd_logo1.png', 'title' => '百度一下,你就知道', 'alt' => '百度' ), ); $jsonstr = json_encode($arr); // 转换成json数据存储格式 echo $jsonstr; ?>
下面是结果,将从php传来的json数据解析后赋给img标签: