4、封装的ajax url带参数通过接口调用数据实例
封装ajax
function ajax(method, url, data, success) { //method 数据提交方式(get、post) url 地址 data ?后面跟着的参数 success 成功后执行 var xhr = null; try { //或者用if(window.XMLHttpRequest) else 来判断 xhr = new XMLHttpRequest(); } catch (e) { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // method 数据提交方式(get、post)类型的判断 if (method == 'get' && data) { url += '?' + data; } xhr.open(method,url,true); if (method == 'get'){ xhr.send(); } else { xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.send(data); } xhr.onreadystatechange = function() { if ( xhr.readyState == 4 ){ if ( xhr.status == 200 ){ // success && success(xhr.responseText);//如果success存在就执行success(xhr.responseText); if(success){//或者写if-else success(xhr.responseText); } } else { alert('出错了,Err:' + xhr.status); } } } }
php文件(
http://www.wookmark.com/api/json/popular?page= 因为要解决跨域的问题,所以才把这个链接在丢到php里面然后再引用它
)
<?php header('Content-type:text/html; charset="utf-8"'); /* API: getPics.php 参数 cpage : 获取数据的页数 */ $cpage = isset($_GET['cpage']) ? $_GET['cpage'] : 1; $url = 'http://www.wookmark.com/api/json/popular?page=' . $cpage; $content = file_get_contents($url); $content = iconv('gbk', 'utf-8', $content); echo $content; ?>
html文件
</style> </head> <body> <ul id="ul1"> <li></li> <li></li> <li></li> <li></li> </ul> </body> <script src="ajax.js"></script> <script> var oUl = document.getElementById('ul1'); var aLi = oUl.getElementsByTagName('li'); var iPage = 3; //因为有cpage这个参数 ajax('get','getPics.php','cpage=' + iPage,function(data) { var data = JSON.parse(data); for ( var i=0; i<data.length; i++ ) { var oImg = document.createElement('img'); oImg.src = data[i].preview; oImg.style.width = '225px'; oImg.style.height = data[i].height * ( 225 / data[i].width ) + 'px'; aLi[i].appendChild( oImg ); } }); </script> </html>


浙公网安备 33010602011771号