3、不封装ajax 带url参数调用接口实例

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>
<style type="text/css">
      *{margin: 0; padding: 0;list-style: none;}   
</style>
<body>
      <ul id="ul1">
          <li></li>
      </ul>
</body>
        <script type="text/javascript">
        var oUl = document.getElementById('ul1');
        var aLi = oUl.getElementsByTagName('li');
        var iPage = 1; //因为有cpage这个参数 分页的作用
 
        var xhr = null;
        try {
            xhr = new XMLHttpRequest();
        } catch (e) {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
            xhr.open('get','getPics.php?cpage='+iPage,true);

            xhr.send();


            xhr.onreadystatechange=function(){
                  if(xhr.readyState===4){
                      if(xhr.status===200){

                        var data = JSON.parse(xhr.responseText);
                            // 遍历并创建一个img元素通过接口的数据调用,将其插入到li中
                          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 );
                                // Cannot read property 'appendChild' of undefined  控制台报这个错误的原因是只有一个li,但是data.length的长度又不止一个,所以插入到后面时,发现没有li了可以多加几个li标签(data.length的长度决定加多少才不会报这个错),所以将 aLi[i]改成 aLi[0],获取第零个元素,并插入到里面去,就可以在li元素里面插入全部的img,而不用查看后面的li元素的多少
                          }

                      }else{

                     alert('调取失败'+xhr.status)
                  }
                      
                  }
            }

               
        </script>
</html>

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;

?>

 

posted @ 2016-12-25 18:25  xuanPhoto  阅读(215)  评论(0)    收藏  举报