zoukankan      html  css  js  c++  java
  • 自己封装的AJAX (带JSON)

    最简单的封装的AJAX:

    function myajax(url,onsuccess,fail){
        //确定是否支持xhr
        var xhr = new XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
        //准备发送post异步请求
        xhr.open('POST', url, true);
        //监听并获得返回结果
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) { //4 表示执行完
                if (xhr.status == 200) { //200 表示执行成功
                    onsuccess(xhr.responseText);
                } else {
                    if (fail) { //有传fail才传出失败信息
                        fail(xhr.status);
                    }
                }
            }
        }
        //发送请求
        xhr.send();
    }
    myajax.js

    可以把json字符串转JavaScript对象的AJAX

    function myajaxjson(url, onsuccess, fail) {
        //确定是否支持xhr
        var xhr = new XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
        //准备发送post异步请求
        xhr.open('POST', url, true);
        //监听并获得返回结果
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) { //4 表示执行完
                if (xhr.status == 200) { //200 表示执行成功
                    if (xhr.getResponseHeader('Content-Type').indexOf('application/json') >= 0) { //响应头中'Content-Type是application/json,则把json字符串转js对象
                        var jsObj = eval('(' + xhr.responseText + ')');
                        onsuccess(jsObj);
                    } else {
                        onsuccess(xhr.responseText);
                    }
                } else {
                    if (fail) { //有传fail才传出失败信息
                        fail(xhr.status);
                    }
                }
            }
        }
        //发送请求
        xhr.send();
    }
    myajaxjson.js
  • 相关阅读:
    48. Rotate Image
    83. Remove Duplicates from Sorted List
    46. Permutations
    HTML5笔记
    18. 4Sum
    24. Swap Nodes in Pairs
    42. Trapping Rain Water
    Python modf() 函数
    Python min() 函数
    Python max() 函数
  • 原文地址:https://www.cnblogs.com/adolphyang/p/4803278.html
Copyright © 2011-2022 走看看