ajax
ajax_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" onclick="a()"/>
</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[name] = Array(value, false);
};
this.encVar = function(name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = 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[i].split("=");
if (true == encode){
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}
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 URLString
this.setVar("rndval", new Date().getTime());
urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
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[0] = self.xmlhttp.status;
self.responseStatus[1] = 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[0] == "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 跨域[size=large][/size]
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[0].name);
}
);
}
</script>
</head>
<body>
This is my HTML page.
<input type="button" value="root1" id="root1" onclick="a()"/>
</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'} ] )");
%>
分享到:
相关推荐
ajax跨域
本资源主要介绍了AJAX跨域的解决办法,以及解决方案间的比较
一个c# ajax跨域的demo,解决c# ajax 跨域的问题
Spring Boot 使用 Redis 进行配置 Session 共享(Ajax 跨域) 源码下载。
ajax跨域调用wcf实例
怎样实现Ajax 跨域访问的五种方法, 怎样实现Ajax 跨域访问的五种方法
解决ajax跨域问题
可以将book.aa.com用iframe添加到 www.aa.com的某个页面下,在www.aa.com和iframe里面都加上document.domain = "aa.com",这样就可以统一域了,可以实现跨域访问。就和平时同一个域中镶嵌iframe一样,直接调用里面的...
利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据
解决ie8、9Ajax跨域问题(前端):jsp引入此js,Jquery Ajax正常写
Ajax跨域问题及其解决方案.docx
Ajax跨域问题详解,包括详解内容、java代码、nginx等详细信息,可以直接运行
你需要获取其他网站的数据吧,ajax跨域获取数据帮你实现。
Ajax跨域访问的示例(ASP.NET Web)
使用juery提交表单,实现ajax跨域请求
ajax跨域问题的解决办法
在收集AJAX面试题的时候其实就已经有过AJAX跨域的问题的了,当时候知道了为什么会存在跨域,以及跨域解决的方案有哪些,今天随着课程的学习,又加深了AJAX跨域的理解,以此记录下来。
基于ajax方式的跨域请求jsonp的前后台代码