Ajax跨域问题
1引言
说到AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交换数据?第二个是跨域的需求如何解决? 这两个问题目前都有不同的解决方案,但到目前为止最被推崇或者说首选的方案还是用JSON来传数据,靠JSONP来跨域。接下来我们就讲解一下Ajax跨域的问题。
1.1什么是跨域?
简单的来说,出于安全方面的考虑,页面中的JavaScript无法访问其他服务器上的数据,即“同源策略”。而跨域就是通过某些手段来绕过同源策略限制,实现不同服务器之间通信的效果。
1.2JSONP跨域的原理
在同源策略下,在某个服务器下的页面时无法获取到该服务器以外的数据的,但img、iframe、script等标签是个例外,这些标签可以通过src属性请求到其他服务器上的数据。利用script标签的开放策略,我们可以实现跨域请求数据,当然,也需要服务端的配合。当我们正常的请求一个JSON数据的时候,服务端返回的是一串JSON类型的数据,而我们使用JSONP模式来请求数据的时候,服务端返回的是一段可执行的javaScript代码。
2代码
客户端代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="D:\develop\jquery-easyui\jquery\jquery-1.9.1.min.js"></script>
</head>
<script type="text/javascript">
$(function(){
$.ajax({
type : "get",
async:false,
url: "http://localhost:8080/SpringMVC_demo/base/json.do?sid=1494&busiId=101",
dataType : "jsonp",//数据类型为jsonp
jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data){
alert(data.result);
$("#showcontent").text("Result:"+data.result)
},
error:function(){
alert('fail');
}
});
});
</script>
<body>
<div id="showcontent">Result:</div>
</body>
</html>
服务器端代码:
package sina.com.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ExchangeJsonController {
@RequestMapping("/base/json.do")
public void exchangeJson(HttpServletRequest request,HttpServletResponse response) {
try {
response.("text/plain");
//防止JSP或者Servlet中的输出被浏览器保存在缓冲区中
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
Map<String,String> map = new HashMap<String,String>();
map.put("result", "123");
PrintWriter out = response.getWriter();
JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json
String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
System.out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");
out.println(jsonpCallback+"("+resultJSON.toString()+")");//返回jsonp格式数据
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
访问时先运行服务端,在访问网页