Spring MVC + AJAX + Jquery ajax callback to success function is not working
2014-09-02 17:37
597 查看
There is some problem with callback function of Ajax by returning string value from Spring Controller. I want the image to be uploaded asynchronously, Upload is successful but the page is redirecting to the another page and the callback function is not called.
JSP: image-upload.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>some title</title>
<script src="<c:url value="/resources/scripts/jquery.js" />"></script>
<link rel="stylesheet" href="<c:url value="/resources/css/jquery-ui.css" />">
<script src="<c:url value="/resources/scripts/jquery-ui.js" />"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#popsave").click(function(e){
$.ajax({
url: $("#uploadform").attr( "action"),
data: {fileToUpload : formData},
type: 'POST',
cache: false,
processdata: false,
contentType : false,
async: true,
dataType: "json",
mimeType: "application/json",
success: function(data){
alert(JSON.stringify(data));
},
error: function(){
alert("something went wrong");
}
});
e.preventDefault();
return false;
});
});
</script>
</head>
<body>
<!-- image uploading pop up -->
<form method="post" action="/SampleUpload/uploadfile" id="uploadform" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload" />
<table style="align:center;"><tr><td><input id="popsave" type="submit" value="Save" /></td><td><input id="cancelBtn" type="button" value="cancel"/></td></tr></table>
<img id="cancelpop" style="width:20px;height:20px;position: absolute;top:-15px;right:-15px;" src="<c:url value='/resources/images/cancel.png'/>" alt="cancel"/>
</form>
</body>
</html>
My Controller:
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public @ResponseBody String uploadImage(HttpServletRequest request, @RequestParam(value = "fileToUpload") MultipartFile image) throws IOException {
String fileName = image.getOriginalFilename();
String imageurl = "";
try {
if(fileName != ""){
String path = (String) request.getSession().getServletContext().getRealPath("/");
String rndfilename = RandomStringUtils.randomAlphanumeric(20);
File file = new File(path+"resources/tempuploads/"+ rndfilename + fileName);
imageurl = path+"resources/tempuploads/"+ rndfilename + fileName;
fileName = file.toString();
FileUtils.writeByteArrayToFile(file, image.getBytes());
System.out.println("Go to the location: " + file.toString()
+ " on your computer and verify that the image has been stored.");
}
} catch (IOException e) {
throw e;
}
return imageurl;
}
The "imageurl"
should be returned to my current jsp page(image-upload.jsp) and have to show an alert msg. But it is showing the "imageurl" on the other page (showing on the URL which we have called in ajax i.e http://www.test.com/SampleUpload/uploadfile).
There is no page with name 'uploadfile'. I have tried different ways but didn't worked. Please help me to fix it ( I want to return the image url to our ajax callback function and have to show alert msg in the same page and the page shouldn't be reloaded or
refreshed or redirected). I am also using Spring security in my application.
Answer:
Remove the action attribute from the form, and directly give URL in your ajax call.
JSP: image-upload.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>some title</title>
<script src="<c:url value="/resources/scripts/jquery.js" />"></script>
<link rel="stylesheet" href="<c:url value="/resources/css/jquery-ui.css" />">
<script src="<c:url value="/resources/scripts/jquery-ui.js" />"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#popsave").click(function(e){
$.ajax({
url: $("#uploadform").attr( "action"),
data: {fileToUpload : formData},
type: 'POST',
cache: false,
processdata: false,
contentType : false,
async: true,
dataType: "json",
mimeType: "application/json",
success: function(data){
alert(JSON.stringify(data));
},
error: function(){
alert("something went wrong");
}
});
e.preventDefault();
return false;
});
});
</script>
</head>
<body>
<!-- image uploading pop up -->
<form method="post" action="/SampleUpload/uploadfile" id="uploadform" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload" />
<table style="align:center;"><tr><td><input id="popsave" type="submit" value="Save" /></td><td><input id="cancelBtn" type="button" value="cancel"/></td></tr></table>
<img id="cancelpop" style="width:20px;height:20px;position: absolute;top:-15px;right:-15px;" src="<c:url value='/resources/images/cancel.png'/>" alt="cancel"/>
</form>
</body>
</html>
My Controller:
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public @ResponseBody String uploadImage(HttpServletRequest request, @RequestParam(value = "fileToUpload") MultipartFile image) throws IOException {
String fileName = image.getOriginalFilename();
String imageurl = "";
try {
if(fileName != ""){
String path = (String) request.getSession().getServletContext().getRealPath("/");
String rndfilename = RandomStringUtils.randomAlphanumeric(20);
File file = new File(path+"resources/tempuploads/"+ rndfilename + fileName);
imageurl = path+"resources/tempuploads/"+ rndfilename + fileName;
fileName = file.toString();
FileUtils.writeByteArrayToFile(file, image.getBytes());
System.out.println("Go to the location: " + file.toString()
+ " on your computer and verify that the image has been stored.");
}
} catch (IOException e) {
throw e;
}
return imageurl;
}
The "imageurl"
should be returned to my current jsp page(image-upload.jsp) and have to show an alert msg. But it is showing the "imageurl" on the other page (showing on the URL which we have called in ajax i.e http://www.test.com/SampleUpload/uploadfile).
There is no page with name 'uploadfile'. I have tried different ways but didn't worked. Please help me to fix it ( I want to return the image url to our ajax callback function and have to show alert msg in the same page and the page shouldn't be reloaded or
refreshed or redirected). I am also using Spring security in my application.
Answer:
Remove the action attribute from the form, and directly give URL in your ajax call.
相关文章推荐
- jquery TypeError: 'undefined' is not a function (evaluating 'elem.nodeName.toLowerCase()') [jquery.js:1904]错误原因
- AJAX问题:jQuery.handleError is not a function
- ajaxfileupload.js上传文件时jQuery.handleError is not a function的 解决办法
- jquery.form.js关于$("form").ajaxSubmit is not a function原因 .
- ajaxfileupload.js jQuery.handleError is not a function
- 小程序this.setData is not a function;api request success callback function解决方法
- jquery.form.js关于$("form").ajaxSubmit is not a function原因 .
- jQuery.form Ajax无刷新上传报错 (jQuery.handleError is not a function) 解决办法
- ajaxfileupload.js结合低版本jquery报异常:TypeError: jQuery.handleError is not a function
- TypeError: a(...).live is not a function(jquery.unobtrusive-ajax.min.js 引入报错)
- JQuery:$(...).ajaxSubmit is not a function
- [Spring MVC] What is my Spring MVC controller not working?
- jQuery.form Ajax无刷新上传错误 (jQuery.handleError is not a function) 解决方案
- ajaxFileUpload :jQuery.handleError is not a function的解决方法
- jquery中Uncaught TypeError: $(...).ajaxUpload is not a function(…)错误解决方法
- 通过jquery dialog为什么提交不了form表单 和 $("#Form").ajaxSubmit(options) is not a function 的原因
- jQuery.form Ajax无刷新上传报错 (jQuery.handleError is not a function) 解决办法
- jquery-ui.min.js:5 Uncaught TypeError: b.nodeName.toLowerCase is not a function
- How to solve “jQuery not working in AJAX loaded elements”
- jquery 报错 e.nodeName.toLowerCase is not a function