[JS]笔记19_AJAX跨域(demo)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/express_yourself/article/details/53068349

注:服务器环境运行!

test05.php文件:

<?php
    $str='{"name":"薯片","sex":"女","age":19,"score":66}';
    echo $str;
?>

1、同步请求

xhr.open(‘get’,’test05.php?_=’+new Date().getTime(),false)
//同步请求–>同步执行

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>同步请求</title>
</head>
<body>
<button id="btn">请求数据</button>
<h1 id="list"></h1>
<script>
    var list=document.getElementById('list');
    var btn=document.getElementById('btn');
    btn.onclick=function(){
        //1、创建XMLHttpRequest对象
        if (window.XMLHttpRequest) {//非IE5 6
            var xhr=new XMLHttpRequest();//实例对象
        }else{//IE5 6
            var xhr=new ActiveXObject('Microsoft.XMLHTTP');
        }
        //2、打开与服务器的链接
        xhr.open('get','test05.php?_='+new Date().getTime(),false)//同步请求-->同步执行
        //3、发送给服务器
        xhr.send(null);//空或null--get请求
        //4、响应就绪---异步请求
        /*xhr.onreadystatechange=function(){
            if (xhr.readyState==4) {//请求完成
                if (xhr.status==200) {//OK-->表示响应已就绪
                    list.innerHTML=xhr.responseText;
                    console.log('完成数据请求!');
                }else{
                    alert(xhr.status);
                };
            };
        };*/
        //4、响应就绪---同步请求
        var json=JSON.parse(xhr.responseText);
        console.log(json);
        // {name: "薯片", sex: "女", age: 19, score: 66}
        list.innerHTML=json.name;
        console.log('完成数据请求!');

        //其他程序
        console.log('其他程序');
    }
</script>
</body>
</html>

打印结果:

Object {name: "薯片", sex: "女", age: 19, score: 66}
同步请求.html:40 完成数据请求!
同步请求.html:43 其他程序

同步请求,ajax请求的代码会和页面的其他代码,按先后顺序执行。

2、post请求

xhr.open(‘post‘,’test05.php?‘,true);
//post 请求–添加http头部
xhr.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);
//3、发送给服务器
xhr.send(‘user=laowang_=’+new Date().getTime());//post请求

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>post请求</title>
</head>
<body>
<button id="btn">请求数据</button>
<h1 id="list"></h1>
<script>
    var list=document.getElementById('list');
    var btn=document.getElementById('btn');
    btn.onclick=function(){
        //1、创建XMLHttpRequest对象
        if (window.XMLHttpRequest) {//非IE5 6
            var xhr=new XMLHttpRequest();//实例对象
        }else{//IE5 6
            var xhr=new ActiveXObject('Microsoft.XMLHTTP');
        }
        //2、打开与服务器的链接
        xhr.open('post','test05.php?',true)//常用异步--true-->最后执行
        //post 请求--添加http头部
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        //3、发送给服务器
        xhr.send('user=laowang_='+new Date().getTime());//post请求
        //4、响应就绪---异步请求
        xhr.onreadystatechange=function(){
            if (xhr.readyState==4) {//请求完成
                if (xhr.status==200) {//OK-->表示响应已就绪
                    var json=JSON.parse(xhr.responseText);
                    list.innerHTML=json.name;
                    console.log('完成数据请求!');
                }else{
                    alert(xhr.status);
                };
            };
        };
        //其他程序
        console.log('其他程序');
    }
</script>
</body>
</html>

打印结果:

其他程序
post请求.html:32 完成数据请求!

异步请求所有的请求过程会等到页面其他代码执行完后,最后执行。

3、ajax函数封装

ajax.js:

function ajax(Url,successFn,failureFn){
    //1、创建XMLHttpRequest对象
    if (window.XMLHttpRequest) {//非IE5 6
        var xhr=new XMLHttpRequest();//实例对象
    }else{//IE5 6
        var xhr=new ActiveXObject('Microsoft.XMLHTTP');
    }
    //2、打开与服务器的链接
    xhr.open('get',Url,true)//常用异步--true-->最后执行
    //3、发送给服务器
    xhr.send(null);//空或null--get请求
    //4、响应就绪---异步请求
    xhr.onreadystatechange=function(){
        if (xhr.readyState==4) {
            if (xhr.status==200) {
                successFn(xhr.responseText);//请求成功
            }else{
                if (failureFn) {
                    failureFn();//请求失败
                }else{
                    alert(xhr.status);
                }
            };
        };
    };
}

ajax函数封装应用:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>封装</title>
</head>
<body>
<button id="btn">请求数据</button>
<h1 id="list"></h1>
<script src="ajax.js"></script>
<script>
    var list=document.getElementById('list');
    var btn=document.getElementById('btn');
    btn.onclick=function(){
        ajax('test05.php?_='+new Date().getTime(),function(str){
            var json=JSON.parse(str);
            // {name: "薯片", sex: "女", age: 19, score: 66}
            list.innerHTML=json.name+json.sex+json.age;
        },function(){
            alert('连接失败!')
        })
        //其他程序
        console.log('其他程序');
    }
</script>
</body>
</html>

4、ajax函数应用 -百度关键字

baidu2.php:

<?php
    header("Access-Control-Allow-Origin:*");
    // $url='http://suggestion.baidu.com/su?wd=';//由服务器来获取数据
    $url=$_GET['sc'];//页面传过来数据地址,由服务器去获取
    function getJSONStr($str){
        return substr($str,17);
    }

    function crul($key){
        global $url;
        $data = file_get_contents($url.$key);
        $data = getJSONStr($data);
        $data = str_replace("{q:\"","",$data);
        $data = str_replace("\",p:","{%aaa%}",$data);
        $data = str_replace(",s:[","{%aaa%}",$data);
        $data = str_replace("]});","",$data);
        $arr = explode("{%aaa%}",$data);
        $res = array();
        $res['q'] = iconv("GB2312","UTF-8",$arr[0]);

        if ($arr[1] == 'true'){
            $arr[1] = true;
        }else{
            $arr[1] = false;
        }

        $res['p'] = $arr[1];

        if (strlen($arr[2])>0){
            $arr[2] = substr($arr[2],1,-1);
            $arr[2] = str_replace("\",\"",",",$arr[2]);
            $arr[2] = iconv("GB2312","UTF-8",$arr[2]);
        }

        $res['s'] = explode(',',$arr[2]);
        echo json_encode($res);//json_encode()转换成json字符串
    }

    $key = $_REQUEST['wd'];
    crul($key);
?>

baidu2-keyword-ajax.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>baidu</title>
<style>
*{margin:0;padding:0;list-style: none;}
#box{width:500px;margin:30px auto 0;padding:10px;background: #e3e3e3;}
#ipt{width:496px;line-height: 30px;font-size: 18px;color:blue;}
#list{margin-top:10px;background: #e3e3e3;}
#list li{line-height: 26px;font-size: 16px;color: blue;padding: 0 10px;}
#list li:hover{background: #ccc;}
</style>
</head>
<body>
<div id="box">
    <input id="ipt" type="text">
    <ul id="list">
        <!-- <li>123fd</li>
        <li>213213</li> -->
    </ul>
</div>
<script src="ajax.js"></script>
<script>
    var ipt=document.getElementById('ipt');
    var list=document.getElementById('list');
    ipt.onkeyup=function(){
        list.innerHTML='';
        ajax('baidu2.php?wd='+ipt.value+'&sc=http://suggestion.baidu.com/su?wd=&t='+new Date().getTime(),function(str){
            var json=JSON.parse(str);
            /*["12306铁路客户服务中心", "12306火车票网上订票官网", "12306退票手续费", "12306.cn", "12306身份信息待核验要多久", "12306验证码识别",…]*/
            for (var i = 0; i < json.s.length; i++) {
                list.innerHTML+='<li>'+json.s[i]+'</li>';
            }
        })
    }
</script>
</body>
</html>

运行结果:
这里写图片描述

5、ajax函数应用 -login-ajax

login.php:

<?php
/*****************************************************

    请求方式: get

    url:    form.php?user=用户名&pass=密码

    return: '登陆成功'
            '账号密码不能为空'
            '账号错误'
            '密码错误'

*****************************************************/
$user=$_GET["user"];
$pass=$_GET["pass"];

// $user=$_POST["user"];
// $pass=$_POST["pass"];

if ($user=="lolo"&&$pass=="2303"){
    echo '登陆成功';
}else{
    if ($user==""||$pass=="") {
        echo '账号密码不能为空';
    } else if ($user!="laowang"){
        echo '账号错误';
    }else if ($pass!="12345"){
        echo '密码错误';
    };
};

?>

login-ajax.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login-ajax</title>
<style>
#wrap{
    width:200px;
    margin:20px auto;
}
</style>
</head>
<body>
<form id="wrap">
    <input id="user" type="text">
    <input id="pass" type="text">
    <button id="btn">登录</button>
</form>
<script src="ajax.js"></script>
<script>
    var user=document.getElementById('user');
    var pass=document.getElementById('pass');
    var btn=document.getElementById('btn');
    btn.onclick=function(){
        ajax('login.php?user='+user.value+'&pass='+pass.value+'&t='+new Date().getTime(),function(str){
            alert(str);
        });
    }
</script>
</body>
</html>

6、用form请求-login-form

login-from.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login-form</title>
<style>
#wrap{width:200px;margin:20px auto;}
</style>
</head>
<body>
<form id="wrap" method="get" action='login.php'>
    <input id="user" type="text">
    <input id="pass" type="text">
    <button id="btn">登录</button>
</form>
</body>
</html>

把请求的路径放在form的属性action里面;请求方法放在method里面

7、通过接口文档声明的ajax请求

#wrap{width:600px;margin:20px auto;background: #eee;list-style: none;}
</style>
</head>
<body>
    <div id="wrap">
        <button id="btn">获取汽车信息</button>
        <ul id="con">
        </ul>
    </div>
<script src="ajax.js"></script>
<script>
    var btn=document.getElementById('btn');
    var con=document.getElementById('con');
    btn.onclick=function(){
        ajax('http://sjz.bokanedu.com/tgr/api/index.aspx?day=4-2&type=car&_='+new Date().getTime(),function (str){
                var json=eval('('+str+')')//解析成json对象
                console.log(json);
                if (json.code==0) {
                    for (var i = 0; i < json.data.batchs.length; i++) {
                        con.innerHTML+='<li>汽车编号:'+json.data.batchs[i].code+';汽车名称:'+json.data.batchs[i].name+'</li>';
                    }
                }else{
                    console.log(json.msg);
                }
        })
        /*{"code":"0",data:{ id: 100001, bin:"JIT-3JS-2",targetBin:"JIT-3JS-3K",batchs:[{code:"JTL-Z38001",name:"奥迪三轮毂"},{ code:"JTL-Z38002",name:"奥迪四轮驱动"}]}}*/
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/express_yourself/article/details/53068349
今日推荐