2

一个演示我只想使用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();
    }
};

使用镀铬显示:

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

谁能帮我?

4

2 回答 2

5

发出 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();
于 2013-04-25T12:46:51.477 回答
0

我得到它:

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
});
于 2013-04-25T13:57:52.930 回答