【问题标题】:How to use native javascript write jquery $.getJSON function?如何使用原生 javascript 编写 jquery $.getJSON 函数?
【发布时间】:2013-04-25 21:57:52
【问题描述】:

一个demo我只想用jquery$.getJSON函数,但现在我必须导入jquery,所以我想用原生javascript写jquery$.getJSON函数。

我的代码是:

var $={
    getJSON: function(url, params, callback){
        var reqUrl = url;
        var xhr = new XMLHttpRequest;
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                JSON.parse(xhr.responseText);
            }
        }
        xhr.open("GET", reqUrl);
        xhr.send();
    }
};

使用 chrome 显示:

XMLHttpRequest cannot load xxxx Origin xx is not allowed by Access-Control-Allow-Origin. 

谁能帮帮我?

【问题讨论】:

  • 为什么不阅读 jquery 源代码并使用它们的实现呢?它肯定比任何人在几分钟内想出的任何东西都更加健壮和经过良好测试。

标签: jquery ajax getjson


【解决方案1】:

发出 ajax 请求并在结果上使用 JSON.parse。比如:

xhr = new XMLHttpRequest;
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        JSON.parse(xhr.responseText);
    }
}
xhr.open("GET", url)
xhr.send();

【讨论】:

    【解决方案2】:

    我明白了:

    var $ = {
        getJSON: function(url, params, callbackFuncName, callback){
            var paramsUrl ="",
                jsonp = this.getQueryString(url)[callbackFuncName];
            for(var key in params){
                paramsUrl+="&"+key+"="+encodeURIComponent(params[key]);
            }
            url+=paramsUrl;
            window[jsonp] = function(data) {
                window[jsonp] = undefined;
                try {
                    delete window[jsonp];
                } catch(e) {}
    
                if (head) {
                    head.removeChild(script);
                }
                callback(data);
            };
    
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.charset = "UTF-8";
            script.src = url;
            head.appendChild(script);
            return true;
        },
        getQueryString: function(url) {
            if(url){
                url = url.split("?")[1];
            }
            var result = {}, queryString = url || location.search.substring(1),
                re = /([^&=]+)=([^&]*)/g, m;
            while (m = re.exec(queryString)) {
                result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
            }
            return result;
        }
    };
    

    调用演示:

    var url = "http://xxx.xxx.xxx?callback=jsonp123";
    var params = {
        a:1,
        b:2
    };
    $.getJSON(url, params, "callback", function(data){
        //todo
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 2012-07-14
      • 2016-08-02
      相关资源
      最近更新 更多