加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax学习

发布时间:2020-12-15 21:33:33 所属栏目:百科 来源:网络整理
导读:Ajax 操作步骤 1、触发一个客户端事件。 2、创建一个 XMLHttpRequest 对象。 var xmlhttp; if ( window .XMLHttpRequest) { // code for IE7+,Firefox,Chrome,Opera,Safari xmlhttp= new XMLHttpRequest(); } else { // code for IE6,IE5 xmlhttp= new Activ

Ajax 操作步骤

1、触发一个客户端事件。

2、创建一个 XMLHttpRequest 对象。

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+,Firefox,Chrome,Opera,Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6,IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

3、打开请求

AjaxRequest.open("GET",url,true);

4、发送请求

如果不需要通过 send() 传递数据,则只要传递 null 作为该方法的参数即可。

AjaxRequest.send(null);

5、XMLHttpRequest设置回调函数。

readyState存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪

AjaxRequest.onreadystatechange = callback;
function callBack() {
                if (AjaxRequest.readyState == 4) {
                    if (AjaxRequest.status == 200) {
                        var resp = AjaxRequest.responseText;
                    } else if (AjaxRequest.status == 404) {
                        alert("Page not found");
                    }
                } else {
                    alert("Error: status code is " + AjaxRequest.status);
                }
            }

Ajax GET

var AjaxRequest;

            function AjaxFunction() {
                try {
                    AjaxRequest = new XMLHttpRequest();
                } catch (e) {
                    try {
                        AjaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                            AjaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {
                            //TODO handle the exception
                            alert("Your browser broke!");
                            return false;
                        }
                    }
                }
            }

            function validateUserId() {
                AjaxFunction();
                var url = "";
                AjaxRequest.open("GET",true);
                AjaxRequest.send(null);
                AjaxRequest.onreadystatechange = callBack();
            }

            function callBack() {
                if (AjaxRequest.readyState == 4) {
                    if (AjaxRequest.status == 200) {
                        var resp = AjaxRequest.responseText;
                    } else if (AjaxRequest.status == 404) {
                        alert("Page not found");
                    }
                } else {
                    alert("Error: status code is " + AjaxRequest.status);
                }
            }

POST

AjaxRequest.open("POST",true);
     AjaxRequest.send(data);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读