ajax上传图片及跨域解决办法(未测试ie)

1.ajax上传图片

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
</head>
<body>
	<div id="uploadForm">
		<input id="file" type="file" name="userfile"/>
		<button id="upload" type="button">upload</button>
	</div>
</body>
</html>
<script type="text/javascript" >

$(function () {
	$("#upload").click(function () {
		var formData = new FormData();
		formData.append('file', $('#file')[0].files[0]);
		$.ajax({
			url: 'http://xxx/uploadFile',
			type: 'POST',
			cache: false,
			data: formData,
			processData: false,
			contentType: false
		}).done(function(res) {
		}).fail(function(res) {});
	});
});
 
</script>

2.ajax跨域

在服务器接收时,只需在response添加响应头Header("Access-Control-Allow-Origin", "*")即可

如:

java:

@RequestMapping(value = "/uploadFile")
@ResponseBody
public String saveApplication(HttpServletRequest request, HttpServletResponse response) {
	response.setHeader("Access-Control-Allow-Origin", "*");
	String result = "success";
	FileUpload fileUpload = new FileUpload();
	UserFile userFile = fileUpload.fileUpload("file", request, response);
	System.out.println(userFile);
	return result;
}
===================================================================

ajax跨域解决,方式2,jsonp方式

前台:

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<script type="text/javascript" src="http://bjzx.xdf.cn:80/scholarship/js/js/jquery-1.10.2.min.js"></script>
</head>
<body>
     
</body>
<script>    
    $(function() {
		$.ajax({
		   type : 'get',
		   async: false,
		   url : 'http://bjmx.xdf.cn/huodong/middleSchoolActivity',
		   dataType : 'jsonp',
		   jsonp: 'jsonpCallback',
		   jsonpCallback:'jsonpCallback',//让后台jsonpCallback参数固定为所填的值,否则是随字字符串
		   success : function(result){
			   console.log(result.result);
			   console.log(result.data);
		   },
		   complete: function(XMLHttpRequest, textStatus){
			
		   },
		   error : function(json,XMLResponse){
			 result = "返回信息:" + json + "错误码:" + XMLHttpRequest.status;
			 console.log("错误信息:" + result);
		   }
		});
	});
</script>
</html>

后台,java springmvc

@RequestMapping(value = "/xxx")
@ResponseBody
public String xxx (String jsonpCallback) {
	Map<String, Object> dataMap = new HashMap<String, Object>();
	String result = "success";
	try {
		
		List<Map<String, Object>> activityList = new ArrayList<Map<String,Object>>();
		//TODO
		dataMap.put("data", activityList);
	}
	catch (NumberFormatException e) {
		e.printStackTrace();
		result = "error";
	}
	dataMap.put("result", result);
	
	String resultStr = com.alibaba.fastjson.JSONObject.toJSONString(dataMap);
	return jsonpCallback + "(" + resultStr + ")";
}



posted @ 2019-12-13 08:36  半湖思絮  阅读(434)  评论(0编辑  收藏  举报