ajax 跨域
ajaxajax_domain_access.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Test Jsonp</title><script type="text/javascript" src="tw-sack.js"></script><script type="text/javascript">var ajax = new sack();function a(){ajax.requestFile = "http://localhost:8080/AjaxDomain/test";ajax.method = "GET";ajax.onCompletion = jsonpCallback;ajax.runAJAX();} function jsonpCallback(result) { alert(result.msg); } </script><script type="text/javascript"src="http://localhost:8080/AjaxDomain/test?jsonp=jsonpCallback"></script></head><body><input type="button" value="root1" id="root1" /></body></html>
tw-sack.js
function sack(file) {this.xmlhttp = null;this.resetData = function() {this.method = "POST";this.queryStringSeparator = "?";this.argumentSeparator = "&";this.URLString = "";this.encodeURIString = true;this.execute = false;this.element = null;this.elementObj = null;this.requestFile = file;this.vars = new Object();this.responseStatus = new Array(2);};this.resetFunctions = function() {this.onLoading = function() { };this.onLoaded = function() { };this.onInteractive = function() { };this.onCompletion = function() { };this.onError = function() { };this.onFail = function() { };};this.reset = function() {this.resetFunctions();this.resetData();};this.createAJAX = function() {try {this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");} catch (e1) {try {this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (e2) {this.xmlhttp = null;}}if (! this.xmlhttp) {if (typeof XMLHttpRequest != "undefined") {this.xmlhttp = new XMLHttpRequest();} else {this.failed = true;}}};this.setVar = function(name, value){this.vars = Array(value, false);};this.encVar = function(name, value, returnvars) {if (true == returnvars) {return Array(encodeURIComponent(name), encodeURIComponent(value));} else {this.vars = Array(encodeURIComponent(value), true);}}this.processURLString = function(string, encode) {encoded = encodeURIComponent(this.argumentSeparator);regexp = new RegExp(this.argumentSeparator + "|" + encoded);varArray = string.split(regexp);for (i = 0; i < varArray.length; i++){urlVars = varArray.split("=");if (true == encode){this.encVar(urlVars, urlVars);} else {this.setVar(urlVars, urlVars);}}}this.createURLString = function(urlstring) {if (this.encodeURIString && this.URLString.length) {this.processURLString(this.URLString, true);}if (urlstring) {if (this.URLString.length) {this.URLString += this.argumentSeparator + urlstring;} else {this.URLString = urlstring;}}// prevents caching of URLStringthis.setVar("rndval", new Date().getTime());urlstringtemp = new Array();for (key in this.vars) {if (false == this.vars && true == this.encodeURIString) {encoded = this.encVar(key, this.vars, true);delete this.vars;this.vars] = Array(encoded, true);key = encoded;}urlstringtemp = key + "=" + this.vars;}if (urlstring){this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);} else {this.URLString += urlstringtemp.join(this.argumentSeparator);}}this.runResponse = function() {eval(this.response);}this.runAJAX = function(urlstring) {if (this.failed) {this.onFail();} else {this.createURLString(urlstring);if (this.element) {this.elementObj = document.getElementById(this.element);}if (this.xmlhttp) {var self = this;if (this.method == "GET") {totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;this.xmlhttp.open(this.method, totalurlstring, true);} else {this.xmlhttp.open(this.method, this.requestFile, true);try {this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")//this.xmlhttp.setRequestHeader("Content-Type", "text/xml;charset=gbk")} catch (e) { }}this.xmlhttp.onreadystatechange = function() {switch (self.xmlhttp.readyState) {case 1:self.onLoading();break;case 2:self.onLoaded();break;case 3:self.onInteractive();break;case 4:self.response = self.xmlhttp.responseText;self.responseXML = self.xmlhttp.responseXML;//alert(self.response);self.responseStatus = self.xmlhttp.status;self.responseStatus = self.xmlhttp.statusText;if (self.execute) {self.runResponse();}if (self.elementObj) {elemNodeName = self.elementObj.nodeName;elemNodeName.toLowerCase();if (elemNodeName == "input"|| elemNodeName == "select"|| elemNodeName == "option"|| elemNodeName == "textarea") {self.elementObj.value = self.response;} else {self.elementObj.innerHTML = self.response;}}if (self.responseStatus == "200") {self.onCompletion();} else {self.onError();}self.URLString = "";break;}};this.xmlhttp.send(this.URLString);}}};this.reset();this.createAJAX();}
testservlet
package com.kanba.ajaxdomain;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Test extends HttpServlet {protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doPost(req, resp);}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();//String string = request.getParameter("username");//if("a".equals(string))//String jsoncallback=request.getParameter("jsoncallback");// //out.print(jsoncallback+"({\"account\":\"XX\",\"passed\":\"true\",\"error\":\"drr\"})");//out.println("jsonpCallback({msg:'this is json data'})");String callback = request.getParameter("callback");out.print(callback + "([{name:\"John\",password:'xuxiangpan'}])");out.flush();out.close();}}
下面是用jquery ajax 跨域
test.html<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>test.html</title><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="this is my page"><meta http-equiv="content-type" content="text/html; charset=UTF-8"><script type="text/javascript" src="jquery-1.3.js"></script><script type="text/javascript"> function a(){$.getJSON("http://root1.kanba.tv:8080/AjaxDomain/test?callback=?",function(json){ //alert(json);alert(json.name); });} </script></head><body>This is my HTML page.<input type="button" value="root1" id="root1" /></body></html>
test对应的servlet
package com.kanba.ajaxdomain;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Test extends HttpServlet {protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doPost(req, resp);}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();String callback = request.getParameter("callback");out.print(callback + "([ { name:\"John\",password:'xuxiangpan'} ] )");out.flush();out.close();}}
用jsp也可以
url test.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String callback = request.getParameter("callback");out.print(callback + "([ { name:\"John\",password:'xuxiangpan'} ] )");%>
页:
[1]