2015-04-22 45 views
2

我有一個Controller,它返回一個用戶列表。當用戶存在時,程序工作正常。但是,當用戶沒有找到時,控制器返回null到jsp頁面,在這種情況下,我得到一個空白屏幕,沒有打印出jsp頁面中的「alert」。請讓我知道爲什麼警報(「用戶不存在」)無法打印,以及當控制器向jsp頁面返回null時如何處理這種情況。Spring MVC控制器向視圖返回空數據

@RequestMapping(value = "/userSearch", 
        method = RequestMethod.POST, 
        produces = "application/json") 
    @ResponseBody 
    public UserList search @RequestParam String username) 
    {  
      UserList userListObj = search(username); // search database 

      if (userListObj.getUserList().size() > 0) 
      { 
       return userListObj; 
      } 
      else 
      { 
       return null; 
      } 
    } 

JSP代碼:

function ajaxUserSearch() 
    { 
     var uname = $("#userName").val(); 
     if (uname) 
     {    
       $.ajax({ 
       type: "POST", 
       url: "userSearch.htm", 
       data: "username=" + uname , 
       dataType: "json", 
       success: function(data) 
       { 
        alert("data=" + data); 
        if (data!=null) 
        {  
          alert("data not null"); 
        } 
        else 
        {    
         alert(" user does not exist, please check"); 
        }     
       },     
       error: function(jqXHR, status, error) 
       { 
        alert("error=" + error + "\nstatus=" + status); 
       }    
      }); 
     } 
     else // If no name is entered but Search button is pressed 
     { 
      alert("Please enter a user name."); 
     } 
} 

回答

0

真的沒有甚至需要檢查userListObj的大小,控制器...只是對象返回頁面:

@ResponseBody 
public UserList search @RequestParam String username) {  
     return search(username); // search database 
} 

然後在您的ajax成功函數中,解析json並檢查長度爲UserList

success: function(data) { 
    var userListObj = $.parseJSON(data); 
    if(userListObj.UserList.length > 0) {  
     alert("data not null"); 
    } else { 
     alert("user does not exist, please check"); 
    } 
1

不返回null。它基本上是一個空的http響應。

在Java代碼中,試圖返回類似:return "notfound"

然後在Javacript success嘗試做這樣的事情:

if (data != null) { 
    if (data === "notfound") { 
    alert("user not found"); 
    } else { 
     alert("user found" + data); 
    } 
} else { 
    alert("unexpected error when finding user. please try again"); 
} 
-1

我通過禁用上的回車鍵解決我自己的問題客戶端輸入字段。

$("form").bind("keypress", function (event) 
      { 
       if (event.keyCode == 13) 
       { 
        event.preventDefault(); 
        return false; 
       } 
      }); 
相關問題