import java.util.HashMap; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; /**
* @author wujing
*/
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController { @CrossOrigin(origins = "http://172.16.71.27:8080")
@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
<script>
$(function() {
$('#title').click(function() {
// alert('点击了');
$.ajax({
url : "http://localhost:8081/api/get",
type : "POST",
data : {
name : "测试"
},
success : function(data, status, xhr) {
console.log(data);
alert(data.name);
}
});
});
})
</script>
特别注意:
1:一定要在某类 或者某方法上 添加类似 method = RequestMethod.POST 的属性
eg: @RequestMapping(value = "/api", method = RequestMethod.POST)
2:在某个方法上添加@CrossOrigin 注解时 origins 属性一定要写ip号 如果输入localhost有时会出现403错误
eg:@CrossOrigin(origins = "http://172.16.71.27:8080")
POST http://localhost:8081/api/get 403 ()
Failed to load http://localhost:8081/api/get: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://172.16.71.27:8080' is therefore not allowed access. The response had HTTP status code 403.
把localhost换成ip 172.16.71.27就可以访问了 。。。