簡體   English   中英

如何解決Ajax成功中的“數據未定義”問題?

[英]How to solve “data undefined” issue in ajax success?

我有一個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>

主控制器.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。

解決方案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()
 {
}

我找到了解決方案:我添加了@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>   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM