How to use native javascript write jquery $.getJSON function?

萝らか妹 提交于 2020-01-23 03:05:30

问题


A demo i only want to use jquery $.getJSON function,but now i must import jquery, so i want to use native javascript write jquery $.getJSON function.

My Code is:

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();
    }
};

use chrome show:

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

who can help me?


回答1:


Make an ajax request and use JSON.parse on the result. Something like:

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



回答2:


i get it:

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;
    }
};

call demo:

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


来源:https://stackoverflow.com/questions/16215061/how-to-use-native-javascript-write-jquery-getjson-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!