如何使用本机javascript写jquery $ .getJSON函数?

一个演示我只想使用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 show:

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

谁能帮我?

发出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(); 

我知道了:

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