動態script標籤解決跨域問題實例

request(jssyncreq.jsp):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
function JSONscriptRequest(fullUrl) {
    this.fullUrl = fullUrl;
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    this.headLoc = document.getElementsByTagName("head").item(0);
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

JSONscriptRequest.scriptCounter = 1;

JSONscriptRequest.prototype.buildScriptTag = function () {

    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "gbk");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}


JSONscriptRequest.prototype.removeScriptTag = function () {
    this.headLoc.removeChild(this.scriptObj); 
}

JSONscriptRequest.prototype.addScriptTag = function () {
    this.headLoc.appendChild(this.scriptObj);
}

function deal(obj) {
    alert(Blog.info);
}

function test() {
    var req = "jssyncres.jsp?callback=deal";
    bObj = new JSONscriptRequest(req);
    bObj.buildScriptTag();
    bObj.addScriptTag();
}

</script>
</head>

<body onload=''>
    <button onclick='test()'>test</button>
</body>
</html>

=========================================================================

response(jssyncres.jsp):

<%
String s1 = request.getParameter("callback");
response.getWriter().print("var Blog = {};Blog.info='test';"+s1+"()"); 
%>
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章