码迷,mamicode.com
首页 > 编程语言 > 详细

javascript中级--ajax(1)

时间:2017-03-08 16:20:50      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:asc   tle   java   html   btn   str   script   请求   odi   

一、ajax.js

function ajax(url, fnSucc, fnFaild) {
    // 1、创建ajax
    var oAjax = null;
    if (window.XMLHttpRequest) {
        var oAjax = new XMLHttpRequest();
    } else {
        var oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2 连接服务器
    oAjax.open(‘GET‘, url, true);
    //3发送请求
    oAjax.send();
    //4接收返回 
    oAjax.onreadystatechange = function() {
        if (oAjax.readyState == 4) { //完成
            if (oAjax.status == 200) { //成功
                fnSucc(oAjax.responseText);
            } else {
                if (fnFaild) {
                    fnFaild();
                }
            }
        }
    }
}

二、实例一--无刷新读取文件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax</title>
    <script src="ajax.js"></script>
    <script>
        //无刷新数据读取,ajax
        window.onload = function() {
            var oBtn = document.getElementById(‘btn1‘)
            oBtn.onclick = function() {
                ajax(‘txt1.txt‘, function(str) {
                    alert(str);
                })
            }
        }
    </script>
</head>

<body>
    点击后读取txt1.txt<br/>
    <input id="btn1" type="button" name="" value="读取">
</body>

</html>

 三、实例二--简单分页

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>简单分页</title>
    <style>
        #div1 {
            width: 400px;
            height: 300px;
            background: #ccc;
            border: 1px solid red;
        }
    </style>
    <script src="ajax.js"></script>
    <script>
        window.onload = function() {
            var aBtn = document.getElementsByTagName(‘input‘);
            var oDiv = document.getElementById(‘div1‘);
            var i = 0;
            for (i = 0; i < aBtn.length; i++) {
                aBtn[i].index = i;
                aBtn[i].onclick = function() {
                    ajax(this.index + 1 + ‘.txt‘, function(str) {
                        oDiv.innerHTML = str;
                    })
                }
            }
        }
    </script>
</head>

<body>
    <input type="button" name="" value="按钮1">
    <input type="button" name="" value="按钮2">
    <input type="button" name="" value="按钮3">
    <div id="div1">

    </div>
</body>

</html>

javascript中级--ajax(1)

标签:asc   tle   java   html   btn   str   script   请求   odi   

原文地址:http://www.cnblogs.com/Mr-W/p/6519915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!