http://localhost:80/
页面请求 http://127.0.0.1:80/
也会有跨域问题XMLHttpRequest cannot load http://你请求的域名. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://当前页的域名' is therefore not allowed access.
jsonp解决跨域问题的原理是,浏览器的script
标签是不受同源策略限制(你可以在你的网页中设置script
的src
属性问cdn服务器中静态文件的路径)。那么就可以使用script标签从服务器获取数据,请求时添加一个参数为callbakc=?,?号时你要执行的回调方法。
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 org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import net.sf.json.JSONObject; //JAVA中使用JSON进行数据传递,用于java生成json字符串,和java解析json字符串 //net.sf.json jar包 @Controller public class JsonpController { @RequestMapping("/base/json.do") public void exchangeJson(HttpServletRequest request,HttpServletResponse response) { try { response.setContentType("text/plain"); 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("name", "content1"); map.put("age", "20"); PrintWriter out = response.getWriter(); JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json String jsonpCallback = request.getParameter("callback");//客户端请求参数 // out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据 System.out.println(resultJSON.toString()); out.println(jsonpCallback+"("+resultJSON.toString()+")");//返回jsonp格式数据 out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="js/jquery-1.4.2.js"></script> </head> <body> <script type="text/javascript"> $(function(){ //方法一 $.getJSON("http://localhost:8080/springmvc0006/base/json.do?sid=1494&busiId=101&callback=?", function(data){ alert(data.name); $("#showcontent").text("Result:"+data.name) }); //方法二 $.ajax({ type : "get", async:false, url : "http://localhost:8080/springmvc0006/base/json.do?sid=1494&busiId=101", dataType : "jsonp",//数据类型为jsonp jsonp: "callback",//服务端用于接收callback调用的function名的参数 success : function(data){ $("#showcontent1").text("Result1:"+data.name) }, error:function(){ alert('fail'); } }); }); //方法三 </script> <script type="text/javascript"> function jsonpCallback(result){ alert(result.name);//jsonpCallback({"name":"content1","age":"20"}) } </script> <script type="text/javascript"src="http://localhost:8080/springmvc0006/base/json.do?sid=1494&busiId=101&callback=jsonpCallback"></script> <div id="showcontent">Result:</div> <div id="showcontent1">Result1:</div> </body> </html>
Access-Control-Allow-Origin
为制定可请求当前域名下数据的域名即可。一般情况下设为即可。这样客户端就不需要使用jsonp来获取数据。