最近公司要跨域請求一個服務,服務未啓動的時候還要報錯。本身作了一個以符合業務需求 貼上源碼: 但願你們能多多提意見 /**
*/
var JSONP = {javascript
now : function() { return (new Date()).getTime(); }, rand : function() { return Math.random().toString().substr(2); }, waitPostArr:[], currentNodeName: "", removeElem : function(elem) { try{ var parent = elem.parentNode; if (parent && parent.nodeType !== 11) { parent.removeChild(elem); } }catch(e){ console.log(e); } }, parseData : function(data) { var ret = ""; if (typeof data === "string") { ret = data; } else if (typeof data === "object") { for ( var key in data) { ret += "&" + key + "=" + encodeURIComponent(data[key]); } } ret += "&_time=" + this.now(); ret = ret.substr(1); return ret; }, getJSONS : function(arr){ this.waitPostArr = arr; this.getJSON(arr[0].url, arr[0].data, arr[0].func); this.waitPostArr.splice(0, 1); }, getJSON : function(url, data, func) { var name; if(url.url){ url = url + (url.url.indexOf("?") === -1 ? "?" : "&") + this.parseData(data); }else{ url = url + (url.indexOf("?") === -1 ? "?" : "&") + this.parseData(data); } var match = /callback=(\w+)/.exec(url); if (match && match[1]) { name = match[1]; } else { name = "jsonp_" + this.now() + '_' + this.rand(); url = url.replace("callback=?", "callback=" + name); url = url.replace("callback=%3F", "callback=" + name); } var script = document.createElement("script"); script.type = "text/javascript"; script.src = url; script.id = "id_" + name; script.onerror = function() { try{ func({ result : "connectFailed" }); }catch(e){ JSONP.JSONP_next(); } }; var head = document.getElementsByTagName("head"); if (head && head[0]) { head[0].appendChild(script); } this.currentNodeName = name; }, JSONP_next : function(){ if(this.waitPostArr && this.waitPostArr.length > 0){ this.getJSON(this.waitPostArr[0].url, this.waitPostArr[0].data, this.waitPostArr[0].func); this.waitPostArr.splice(0, 1); } } }; window["success_jsonpCallback"] = function(json) { var elem = document.getElementById("id_" + JSONP.currentNodeName); JSONP.removeElem(elem); try{ func(json); JSONP.JSONP_next(); }catch(e){ JSONP.JSONP_next() } };
給windows賦函數的時候沒有采起一個請求一個函數是由於後臺服務參數沒有函數名稱(WTF)java