跨域获取json
这两天搞公司网站单点登录,结果打好后一测试发现jsonp在IE下各种报错..............
弄了半天搞不定,索性自己写个出来
好了废话不多说,进入正题
方法名:randomString |
|||
参数名 | 类型 | 说明 | 默认值 |
len | int | 生成字符串长度 | 32 |
说明: | |||
生成随机字符串,这个懒得写直接百度一下Copy过来的 |
function randomString(len) { len = len || 32; var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var maxPos = $chars.length; var pwd = ''; for (i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; }
方法名:RemoteAjax |
|||
参数名 | 类型 | 说明 | 默认值 |
url | string | 请求地址 |
|
data | Key/Value | 参数 |
|
success | function | 成功回调 |
|
error | function | 错误回调 |
|
说明: |
|||
获取远程json,类ajax jsonp 通过动态添加script标签实现,调用时会发送随机串callback,返回时数据格式必须为此callback(JSON) |
function RemoteAjax(insetting){ var objStatus = { complete: false, error: false, requestData: null, responseData: null, init: function(setting){ this.requestData = setting.data; var success = setting.success; var error = setting.error; var tempName = "arebz" + randomString(15); var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script') script.type='text/javascript'; script.charset="GB2312"; script.text = "var " + tempName + "_setting;\r\n" script.text += "function " + tempName + "_init(processor){" + tempName + "_processor = processor;}\r\n"; script.text += "function " + tempName + "_callback(data){" + tempName + "_processor(data);}\r\n"; head.appendChild(script); var remoteScript = document.createElement('script') remoteScript.type='text/javascript'; remoteScript.charset="GB2312"; remoteScript.src = setting.url + "?callback=" + encodeURIComponent(tempName + "_callback"); for(var key in setting.data){ remoteScript.src += "&" + key + "=" + encodeURIComponent(setting.data[key]); } var currentObj = this; if( document.all ){ remoteScript.onreadystatechange = function(){ if(/(complete|loaded)/.test(this.readyState)){ remoteScript.onreadystatechange = null; if(!currentObj.complete){ currentObj.error = true; if(typeof(error) == "function") error(); } } }; }else{ remoteScript.onload = function(){ remoteScript.onload = null; remoteScript.onerror = null; if(!currentObj.complete){ currentObj.error = true; if(typeof(error) == "function") error(); } }; remoteScript.onerror = function(){ remoteScript.onload = null; remoteScript.onerror = null; currentObj.error = true; if(typeof(error) == "function") error(); } } eval(tempName + "_init")(function(data){ currentObj.complete = true; remoteScript.parentNode.removeChild(remoteScript); script.parentNode.removeChild(script); currentObj.responseData = data; if(typeof(success) == "function") success(data); }); head.appendChild(remoteScript); } }; objStatus.init(insetting); return objStatus; }
本文出自 小古Blog,转载时请注明出处及相应链接。
本文永久链接: http://blog.chdz1.com/?post=249