我有一个JSP页面,在其中有一个onclick按钮,我在其中调用一个称为“ sendmail()”的Ajax方法。发送邮件API编写在Controller中。我试图显示警告消息在Ajax中使用data.message成功,它表示数据未定义。
我试图在控制器中将响应对象设置为成功,并将消息字符串返回为字符串。 注意:为此,我必须将控制器的sendmail方法更改为String返回类型。因此,我注意到在这种情况下Ajax调用不会进入成功方法。当该方法的类型为void时,它可以正常工作。在chrome开发人员tolld的帮助下进行了检查,网络调用返回404(未找到)。邮件已成功发送,但ajax成功不起作用。
这是我的按钮和Ajax方法,
<div class="uk-width-large-2-5">
<div class="uk-form-row">
<label>Message</label>
<textarea id="message" cols="30" rows="4" class="md-input"></textarea>
</div>
<div class="uk-form-row">
<button type="submit" class="md-btn md-btn-success md-btn-large" onclick="sendMail()">Send Message</button>
</div>
</div>
Ajax方法:
<script>
function sendMail() {
var reqJson = {};
reqJson.msg = $("#message").val();
$.ajax({
type : "POST",
url : "sendMail",
data : JSON.stringify(reqJson),
dataType: 'json',
contentType: "application/json",
success : function(data) {
console.log("data :"+data.message);
}
error: function()
{
}
});
}
</script>
Maincontroller.java
@RequestMapping(value = "/sendMail", method = RequestMethod.POST, produces = "application/json")
public void sendContact(HttpServletRequest request, HttpServletResponse response, @RequestBody String payload) {
JSONObject jRespObj = new JSONObject();
try {
System.out.println("Welcome");
JSONObject jPayload = new JSONObject(payload);
System.out.println("jobj : "+jPayload);
String message = jPayload.getString("msg");
InputStream inputStream = UserController.class.getResourceAsStream("/Contactusrequest.htm");
StringWriter writer = new StringWriter();
try {
IOUtils.copy(inputStream, writer);
} catch (IOException e) {
e.printStackTrace();
}
HttpSession session = request.getSession(true);
String from = (String) session.getAttribute("email");
String to ="xyz@abc.com";
String emailContent = writer.toString();
emailContent = emailContent.replace("replaceMeFromEmail",from);
emailContent = emailContent.replace("replaceMeToEmail", to);
emailContent = emailContent.replace("replaceMeReason", message);
emailClient.sendMail("", to, null, "Contact Us Request", emailContent);
jRespObj.put("message", "Mail sent successfully");
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception ex) {
ex.printStackTrace();
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return jRespObj.toString();
}
我想从控制器到Ajax成功获取响应对象,以访问data.message。
答案 0 :(得分:0)
解决方案1。您正在返回响应,因此在Ajax中获取数据是未定义的错误。 而不是返回使用Gson或JSONObject在主体中写入json响应。
例如。
//Write the json response in body
//return jRespObj.toString();
response.getWriter().write(jRespObj.toString());
解决方案2 -删除所有其他System.out.println语句并以json之类显示单个响应。
System.out.print(jRespObj.toString());
在ajax中,您可以获得类似
的响应$ajax({
----
success : function(data) {
console.log("data :"+data['message']);
},
error: function()
{
}
答案 1 :(得分:0)
我找到了解决方案: 我添加了@Responsebody并解析了Ajax成功收到的数据。这是我的代码:
@RequestMapping(value = "/sendMessage" ,method = RequestMethod.POST)
@ResponseBody
public String sendMessage(HttpServletRequest request, HttpServletResponse response, @RequestBody String payload) throws JSONException, IOException {
JSONObject jRespObj = new JSONObject();
try {
System.out.println("Welcome");
JSONObject jPayload = new JSONObject(payload);
System.out.println("jobj : "+jPayload);
String message = jPayload.getString("message");
InputStream inputStream = UserController.class.getResourceAsStream("/Contactusrequest.htm");
StringWriter writer = new StringWriter();
try {
IOUtils.copy(inputStream, writer);
} catch (IOException e) {
e.printStackTrace();
}
HttpSession session = request.getSession(true);
String from = (String) session.getAttribute("email");
String to ="xyz@electronosolutions.com";
String emailContent = writer.toString();
emailContent = emailContent.replace("replaceMeFromEmail",from);
emailContent = emailContent.replace("replaceMeToEmail", to);
emailContent = emailContent.replace("replaceMeReason", message);
emailClient.sendMail("", to, null, "Contact Us Request", emailContent);
jRespObj.put("message", "Mail sent succesfully");
} catch (Exception ex) {
ex.printStackTrace();
}
return jRespObj.toString();
}
Ajax方法:
<script>
function sendMessage() {
console.log("page load");
//$("#sendMessage").submit(function(e){
// e.preventDefault();
var reqJson = {};
reqJson.message = $("#message").val();
console.log(reqJson.message+" jhgczjdhgbdzjvh");
$.ajax(
{
url : "sendMessage/",
type: "POST",
data : JSON.stringify(reqJson),
contentType: "application/json",
success:function(data)
{
var msg = JSON.parse(data);
console.log(msg);
UIkit.notify('<a href="#" class="notify-action">Clear</a> ' + msg.message, {
pos : 'top-center',
status:'success',
timeout : 2000
});
setTimeout(function(){ location.reload(); }, 2000);
},
error: function(data)
{
UIkit.notify('<a href="#" class="notify-action">Clear</a> ' + "Mail not sent", {
pos : 'top-center',
status:'warning',
timeout : 6000
});
}
});
}
</script>