Ajax 入门?

一、Ajax代码编写

1。创建对象

    var xhr=new XMLHttpRequest();

        //(第一步,不管三七二十一,先码上再说^_^)

2。连接服务器(准备发送数据)
    xhr.open('get|post',url,true|false);

        //这是连接路径用的.[POSTGET]是获取类型,url是路径,truefalse是异步还是同步,即页面刷新的问题.

        //(总之,接着上面继续码-_-! 但要修改里面的参数,否则可就没意义了.)

3。过程监控
    xhr.onreadystatechange=function(){        //如果变量xhr的状态值发生改变,
    if(this.readyState==4 && this.status==200){      //里面this.readyState==4 && this.status==200  请求(发送)成功是4,相应(返回)成功是200.一般是固定的写法
      ...                      //里面添加内容.(一样的固定写法!*_*!)
    }else{
      ...
     }
    }

(2)获取数据方法:xhr.responseText        
    xhr.responseXML

  
    JSON
    var a={'firstname':'wang','lastname':'frank'}
    JSON.stringify() //转换成字符串
    JSON.parse() //反转成数组值

4。发送数据              
    xhr.send()        //可以理解为结束语句?

二、Ajax代码应用案例
题目:获取长春地区天气情况。

  •   这是php文件,用于获取长春天气的.该网址则是那个天气预报网的长春网址.
<?php 
    $url="http://www.weather.com.cn/data/sk/101060101.html";
    $skinfo=file_get_contents($url);
    print_r($skinfo);
 ?>

输出的结果是:

  {"weatherinfo":{"city":"长春","cityid":"101060101","temp":"30.4","WD":"西风","WS":"小于3级","SD":"23%","AP":"974.8hPa","njd":"暂无实况","WSE":"<3","time":"17:00","sm":"3.1","isRadar":"1","Radar":"JC_RADAR_AZ9431_JB"}}

  • 编写ajax,这里使用html文件编写,内有javascript.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div class="sk">
        <input type="button" value="获取天气预报">   //这是按钮,可以添加onclick=""属性
        <div class="result" onclick=""></div>    //这是要输出内容的div,通过单击按钮,否则将什么也没有.(单击事件加在这里,能好使才见鬼呢!)
    </div>
    <script>
    function abc(){                    //定义一个函数
    var xhr=new XMLHttpRequest();            //创建对象.(第一步)
    var $url="http://localhost/php/tianqi.php";    //获取本地的php路径
    xhr.open('GET',$url,true);              //这里就是上述的连接服务器了,(第二步)
    xhr.onreadystatechange=function(){          //状态值发生改变.(第三步)
        if(4==this.readyState && 200==this.status){  //状态值 4 和 200. 固定数值
            var info=JSON.parse(this.responseText);  //读取php文件中的数据,并转换成数组.然后赋值给info.(就是不知道老师们为何都喜欢用info?)
            console.log(info);              //在后台调试
            var tq="";                  //定义一个新变量;
            tq+="地址:"+info.weatherinfo['city']+'<br>';  //然后通过+=来赋值,+=的效用在于不被覆盖.
            tq+="气温:"+info.weatherinfo['temp']+'<br />';
                document.querySelector('.result').innerHTML=tq;  //这里则是将info变量放进选中的div里,作为里面的内容.
        }                                   //当然,由于被函数包裹了起来,所以一切都需要去调用函数或触发,否则就只能将函数...掐头去尾?
    }                                      //(不知能不能吃?)
    xhr.send();                      //这就是发送数据,做结尾(第四步)
    }
            document.querySelector('input[type=button]').onclick=abc;  //而最后则是函数调用,.虽然onclick事件.(不知这里的函数abc为何没加(),不过却能用.)
    </script>
</body>
</html>

  

原文地址:https://www.cnblogs.com/yinwangyizhi/p/9041596.html