问题
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