JavaScript跨域 --待續

JSONP

思路:儘管瀏覽器不允許頁面中的腳本程序跨域讀取數據,但卻允許HTML引用跨域的資源,如圖片,CSS和腳本程序。

JSONP Client.

JS.

<script type="text/javascript">  
    function jsonpCallback(result){   
       alert(result);  
       alert(result[1].name);  
    }   
</script>
<script type="text/javascript"src="http://localhost:8080/restfull/jsp/jsonp/index.jsp?callback=jsonpCallback"></script>
<!-- 
<script type="text/javascript">   
	$.getJSON("http://localhost:8080/Jsonp/jsonp.jsp?callback=?", function(json){    
		alert(json[0].name);   
	});   
</script>
 -->
<!-- 
<script type="text/javascript"src="http://localhost:8889/jsonp/fff?jsonpCallback"></script>
 -->

JSONP Server.

方法一 jsp

<%
	String callback = request.getParameter("callback");
	out.print(callback+"([ { name:'John',age:'19'},{ name:'joe',age:'20'}] );");
%>
方法二 node.js 參考  node.js learning example

index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.begin;
handle["/begin"] = requestHandlers.begin;
handle["/end"] = requestHandlers.end;
handle["/jsonp/fff"] = requestHandlers.jsonp;
server.start(router.route, handle);
requestHandlers.js
var exec = require("child_process").exec;
function begin(parameter, response){
	console.log("handle the 'begin' call!");
	exec("dir", function(error, stdout, stderr){
		response.writeHeader(200,{"content-type":"text/plain"});
		response.write(stdout);
		response.end();
	});
}
function end(parameter, response){
	console.log("handle the 'end' call!");
		response.writeHeader(200,{"content-type":"text/plain"});
		response.write("end...!");
		response.end();
}
function jsonp(parameter, response){
	console.log("handle the 'end' call!");
		response.writeHeader(200,{"content-type":"text/plain"});
		response.write(parameter+"([ { name:'John',age:'19'},{ name:'joe',age:'20'}] );");
		response.end();
}
exports.begin = begin;
exports.end = end;
exports.jsonp = jsonp;
router.js

function route(handle, pathname, parameter, response){
	console.log("Route the request---------"+pathname);
	if(typeof handle[pathname] === 'function'){
		handle[pathname](parameter, response);
	}else{
		console.log("no request handler found for" + pathname);
		response.writeHead(404,{"content-type":"text/plain"});
		response.write("404 Not Found!");
		response.end();
	}
}
exports.route = route;

server.js

var http = require("http");
var url = require("url");
function start(route,handle){
	function onRequest(request,response){
		console.log("-----------begin-------------");
		var pathname = url.parse(request.url).pathname;
		var search1 = url.parse(request.url).search;
		var parameter = search1.slice(1,search1.length);
		route(handle, pathname, parameter, response);
		console.log("-----------end-------------");
	}
	http.createServer(onRequest).listen(8889);
	console.log("Server is starting...");
}
exports.start = start;

Cross-Origin Resource Sharing (CORS)

CORS Client

cors.js

/**
 * This is for Cross-site Origin Resource Sharing (CORS) requests.
 * 
 * Additionally the script will fail-over to a proxy if you have one set up.
 * 
 * @param string   url      the url to retrieve
 * @param mixed    data     data to send along with the get request [optional]
 * @param function callback function to call on successful result [optional]
 * @param string   type     the type of data to be returned [optional]
 */
function getCORS(url, data, callback, type) {
    try {
        // Try using jQuery to get data
        jQuery.get(url, data, callback, type);
    } catch(e) {
        // jQuery get() failed, try IE8 CORS, or use the proxy
        if (jQuery.browser.msie && window.XDomainRequest) {
            // Use Microsoft XDR
            var xdr = new XDomainRequest();
            xdr.open("get", url);
            xdr.onload = function() {
                callback(handleXDROnload(this, type), 'success', this);
            };
            xdr.send();
        } else {
            try {
                // Ancient browser, use our proxy
                var mycallback = function() {
                    var textstatus = 'error';
                    var data = 'error';
                    if ((this.readyState == 4)
                        && (this.status == '200')) {
                        textstatus = 'success';
                        data = this.responseText;
                    }
                    callback(data, textstatus);
                };
                // proxy_xmlhttp is a separate script you'll have to set up
                request = new proxy_xmlhttp();
                request.open('GET', url, true);
                request.onreadystatechange = mycallback;
                request.send();
            } catch(e) {
                // Could not fetch using the proxy
            }
        }
    }
}

/**
 * This method is for Cross-site Origin Resource Sharing (CORS) POSTs
 *
 * @param string   url      the url to post to
 * @param mixed    data     additional data to send [optional]
 * @param function callback a function to call on success [optional]
 * @param string   type     the type of data to be returned [optional]
 */
function postCORS(url, data, callback, type)
{
    try {
        // Try using jQuery to POST
        jQuery.post(url, data, callback, type);
    } catch(e) {
        // jQuery POST failed
        var params = '';
        for (key in data) {
            params = params+'&'+key+'='+data[key];
        }
        // Try XDR, or use the proxy
        if (jQuery.browser.msie && window.XDomainRequest) {
            // Use XDR
            var xdr = new XDomainRequest();
            xdr.open("post", url);
            xdr.send(params);
            xdr.onload = function() {
                callback(handleXDROnload(this, type), 'success', this);
            };
        } else {
            try {
                // Use the proxy to post the data.
                request = new proxy_xmlhttp();
                request.open('POST', url, true);
                request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                request.send(params);
            } catch(e) {
                // could not post using the proxy
            }
        }
    }
}

/**
 * Because the XDomainRequest object in IE does not handle response XML,
 * this function acts as an intermediary and will attempt to parse the XML and
 * return a DOM document.
 * 
 * @param XDomainRequest xdr  The XDomainRequest object
 * @param string         type The type of data to return
 * 
 * @return mixed 
 */
function handleXDROnload(xdr, type)
{
    var responseText = xdr.responseText, dataType = type || "";
    if (dataType.toLowerCase() == "xml"
        && typeof responseText == "string") {
        // If expected data type is xml, we need to convert it from a
        // string to an XML DOM object
        var doc;
        try {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(responseText);
            } else {
                var parser = new DOMParser();
                doc = parser.parseFromString(responseText, 'text/xml');
            }
            return doc;
        } catch(e) {
            // ERROR parsing XML for conversion, just return the responseText
        }
    }
    return responseText;
}

index.html

<html>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script type="text/javascript" src="cors.js"></script>
	<script type="text/javascript">
		function testGetFromNodeServer()
		{
			getCORS('http://localhost:8889/cros', null, function(data){alert(data);});
		}
		function testGetFromJsp()
		{
			getCORS('http://localhost:8888/test/jsp/date1.jsp', null, function(data){alert(data);});
		}
		function testPost(form)
		{
		    postCORS('http://localhost:8888/test/jsp/date1.jsp', {name: form.name.value}, function(data){alert(data);});
		}
	</script>
	<body>
		<h1>CORS Examples</h1>
		<p>Test GET
		    This page retrieves content from another server, using CORS<br /> 
		    <a href="#" οnclick="testGetFromJsp(); return false;">testGetFromJsp</a>
		    <a href="#" οnclick="testGetFromNodeServer(); return false;">testGetFromNodeServer</a>
		
		</p>
		<p>Test POST:
		    <form action="#" οnsubmit="testPost1(this); return false">
		        Name: <input type="text" name="name" />
		        <input type="submit" />
		    </form>
		</p>
		<a href="http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/">More info</a>
	</body>
</html>


CORS Server

方式一:date1.jsp

<%
	response.setHeader("Access-Control-Allow-Origin","*");
	if (request.getMethod().equals("GET")) {
		out.println("hellow word!");
	}else{
		if (request.getParameter("name") == null) {
	        out.println("Please enter your name.");
	    } else {
	        out.println("Hello <b>"+request.getParameter("name")+"</b>!");
	    }
	}
%>
方式二:node example code
function CROS_testData(parameter, response){
	console.log("handle the 'CROS' call!");
		response.writeHeader(200,{"content-type":"text/plain","Access-Control-Allow-Origin":"*"});
		response.write("hellow!"+parameter);
		response.end();
}

easyXDM







http://raychase.iteye.com/blog/1174397


發佈了33 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章