使用jquery完成跨域访问

2022-07-29,

jquery实现跨域访问有两种方式,一个是$.getJSON,一个是$.ajax,注意只有get请求才能实现跨域访问。

一、$.getJSON实现跨域访问

get.html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>javascript和jquery的跨域访问</title>
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
</head>
<body>
<div>
	  <button id="getJSONNotLocal1">getJSON_跨域访问方式1_通过getJSON函数</button>
 </div>
</body>
<script>
$("#getJSONNotLocal1").click(function(){
	//$.getJSON("http://127.0.0.1:8080/testJsonp/jsonpServlet?a=a_val&callback=?",function(res,sta,xhr){
	//$.getJSON("http://127.0.0.1:8080/testJsonp/jsonpServlet?a=a_val&jsoncallback=?",function(res,sta,xhr){
	$.getJSON("http://127.0.0.1:8080/testJsonp/jsonpServlet?a=a_val&myzdwcallback=?",function(res,sta,xhr){
	//自己定义函数名称是不可以的
	//$.getJSON("http://127.0.0.1:8080/testJsonp/jsonpServlet?a=a_val&myzdwcallback=abcdefg",function(res,sta,xhr){	
		 console.log(res);
		 console.log("跨域访问哦:"+res.info);
		 console.log(res.status);
		 console.log(res.aVal);
		 console.log(sta);
		 console.log(xhr);
	});
});
</script>
</html>

注释:我这里$.getJSON请求的url是另外一个项目的地址,a=a_val我只是传入的参数在后台接受并返回到前端来,跟跨域访问并没有关系;有关系的是后边的第二个参数,我上面写了很多的参数名,意在告诉大家,你的参数名字叫什么没有关系,可以随便起,一般的我们都把它叫做callback,然后他的值是固定的,就是一个"?",当调用成功之后,返回的数据就可以直接在$.getJSON的回调函数里面操作了。

我们来看testJsonp这个项目的java后端是如何写的:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Map<String, Object> map=new HashMap<>();
		map.put("info", "跨域访问成功了");
		map.put("status", "跨域访问ok");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String aVal = request.getParameter("a");
		map.put("aVal", aVal);
		PrintWriter writer = response.getWriter();
		JSONObject jsonObject=JSONObject.fromObject(map);//构造要返回的值
		String retVal="";//最终要返回的值
		
		String callback = request.getParameter("callback");
		String jsoncallback = request.getParameter("jsoncallback");
		String myzdwcallback = request.getParameter("myzdwcallback");
		System.out.println(callback);
		System.out.println(jsoncallback);
		System.out.println(myzdwcallback);
		if (StringUtils.isNotBlank(callback)) {
			retVal=callback+"("+jsonObject.toString()+")";
		}
		if (StringUtils.isNotBlank(jsoncallback)) {
			retVal=jsoncallback+"("+jsonObject.toString()+")";
		}
		if (StringUtils.isNotBlank(myzdwcallback)) {
			retVal=myzdwcallback+"("+jsonObject.toString()+")";
		}
		
		writer.println(retVal);
		writer.flush();
		writer.close();
	}

跟上一篇的代码差不多,不再多说。

执行结果:

java后台打印的日志如下:

其实原理已经很清楚了,$.getJSON帮你封装好了,随机生成了一个函数名字,这个函数名字就相当于上篇文章里面的callByRef2, 如此就实现了jquery的跨域访问了。

二、通过$.ajax实现jquery跨域访问

修改get.html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>javascript和jquery的跨域访问</title>
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
</head>
<body>
<div>
	  <button id="getJSONNotLocal2">getJSON_跨域访问方式2_通过ajax函数</button>
 </div>
</body>
<script>
//使用ajax函数自己定义函数名称是可以的	
$("#getJSONNotLocal2").click(function(){
    $.ajax({
        type: "get",
        async: true,
        url: "http://127.0.0.1:8080/testJsonp/jsonpServlet?a=a_val",
        dataType: "jsonp",
        jsonp: "myzdwcallback",//传递给请求处理程序或页面的,标识jsonp回调函数名(一般为:callback)
        jsonpCallback: "abcdefg",//callback的function名称
        success: function (res) {
        	 console.log(res);
			 console.log("跨域访问哦:"+res.info);
			 console.log(res.status);
			 console.log(res.aVal);
        },
        error: function () {
            alert('fail');
        }
    });
});	
</script>
</html>

 其他都不需要改变,执行结果:

java后台输出:

本文地址:https://blog.csdn.net/xiaozhuangyumaotao/article/details/109240656

《使用jquery完成跨域访问.doc》

下载本文的Word格式文档,以方便收藏与打印。