整理 解决ajax跨域问题

方法一,在java代码中设置response.setHeader("Access-Control-Allow-Origin","*");即可解决ajax跨域的问题,其中星号代表允许全部请求

方法二,使用jsonp的方式请求数据,后端需返回js方法调用,返回的数据放在参数中

例如:返回callbackFunction('{"data":1}')

function testJsonp(){
	$.ajax({
		url:url,
		type:"GET",//必须是get请求
		dataType:"jsonp",//请求的数据类型
		jsonp:"callback",//请求类型是回调
		jsonpCallback:"callbackFunction",//数据请求成功时回调的方法
		data:{	
		},//请求的数据
		success:function(data){//执行完成返回的数据
			alert(data.id);//输出值是1
		}
	});
}


function callbackFunction(res){//回调方法
	alert(res.id);//输出值是1
}

全部代码如下

package com.amysky.system.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class TestController {
	@RequestMapping(value="/testAjaxJsonp")
	public void testAjaxJsonp(@RequestParam String callback,HttpServletResponse response){
		try {
			response.getWriter().print(callback+"({\"id\":1})");
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 使用普通json方式跨域请求
	 * @param response
	 */
	@RequestMapping(value="/testAjaxJson")
	public void testAjaxJson(HttpServletResponse response){
		try {
			response.setHeader("Access-Control-Allow-Origin","*");
			response.getWriter().print("{\"id\":1}");
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>测试ajax跨域请求</title>
		<script src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script>
	</head>
	<body>
		<button onclick="testJsonp();">jsonp跨域请求</button>
		<br/>
		<button onclick="testJson();">json跨域请求</button>
	</body>
<html>
<script>
//--------------------------------------------------jsonp-ajax跨域请求--------------------------------------------
function testJsonp(){
	$.ajax({
		url:"http://localhost:8080/testAjaxJsonp.do",//请求地址
		type:"GET",
		async:false,
		dataType:"jsonp",
		jsonp:"callback",//jsonp请求类型是回调
		jsonpCallback:"callbackFunction",//请求的回调方法
		data:{//传输的参数
		},
		success:function(data){//执行完成返回的数据
			alert("后执行"+data.id)//1
		}
	});
}

function callbackFunction(res){//回调方法
	alert("先执行"+res.id)//1
}

//--------------------------------------------------普通ajax跨域请求--------------------------------------------
function testJson(){
	$.ajax({
		url:"http://localhost:8080/testAjaxJson.do",//请求地址
		type:"POST",
		async:false,
		dataType:"json",
		data:{//传输的参数
		},
		success:function(data){//执行完成返回的数据
			alert(data.id)//1
		}
	});
}
</script>




猜你喜欢

转载自blog.csdn.net/u012722296/article/details/78597297