2012-06-14 115 views
2

是否可以在沒有刷新的情況下在SPRING MVC 3中提交表單?無刷新提交表單(SPRING MVC 3)

我想要的是將數據以SPRING形式存儲到java object/POJO。

這裏是我的map.jsp

<form:form action="" method="post" commandName="userQuery">  
    <form:input path="startLocation" id ="startLocation" /> 
<input type="submit" value="Search" onclick="codeAddress()"> 

<script type="text/javascript"> 
    function codeAddress(){ 
     var address = document.getElementById("startLocation").value;     
     geocoder.geocode({ 'address': address, 'partialmatch' : true }, geoCodeResults);     
</script> 

我想的數據(即startLocation)存儲Java對象,在同一時間使用的是JavaScript的數據,所以我可以顯示谷歌地圖並在該位置顯示標記。但我每次提交表單時,它刷新頁面,於是,該標記不呈現,因爲它重新加載整個頁面,包括地圖

這裏是我的Controller.java

@RequestMapping(value= "/map" , method = RequestMethod.GET) 
public ModelAndView showMap(){ 
    ModelAndView mav = new ModelAndView("home/map"); 
    Query query = new Query(); 
    mav.getModel().put("userQuery", query);     
    return mav;   
} 

    @RequestMapping(value="/map", method = RequestMethod.POST) 
public ModelAndView createMap(@ModelAttribute("userQuery") Query query){     
    ModelAndView mav = new ModelAndView("home/map");   
    List<Query> q = new ArrayList<Query>();   
    q.add(new Query(query.getStartLocation()));       
    mav.addObject("q", q);   
    return mav;   
} 

我需要存儲startLocation。請幫忙。除了SPRING表單之外,還有其他方法可以存儲用戶輸入嗎?

回答

1

你在做什麼很好。但是你只是缺少的一件事是從Java腳本函數中'返回false'。因爲你正在從表單提交按鈕調用該函數,所以在成功處理你的ajax請求之後,它也會提交表單。所以你需要停止。

希望這可以幫助你。乾杯。

2

我會看看使用jQuery JavaScript庫與jQuery form插件。它使用AJAX發佈表單(即不重新加載整個頁面)更容易。

1

我想下面的代碼將幫助您

撥打以下事件JavaScript方法,當你想更新開始位置 addStartLocation方法需要在你的情況,而不是提交按鈕點擊被稱爲「codeAddress()」方法

var xmlHttp; 
      function addStartLocation(){ 
       if (typeof XMLHttpRequest != "undefined"){ 
        xmlHttp= new XMLHttpRequest(); 
       } 
       else if (window.ActiveXObject){ 
        xmlHttp= new ActiveXObject("Microsoft.XMLHTTP"); 
       } 
       if (xmlHttp==null){ 
        alert("Browser does not support XMLHTTP Request") 
        return; 
       } 
       var url="/project/updateStartLocation"; 
       url +="?location=" +document.getElementById("location").value; 
       xmlHttp.onreadystatechange = displayMap; 
       xmlHttp.open("GET", url, true); 
       xmlHttp.send(null); 
      } 

function displayMap() { 
// Here you can right geocode to display map 
} 

然後在Spring MVC控制器處理這樣

@RequestMapping(value = "/updateStartLocation", method = RequestMethod.GET) 
    public @ResponseBody String updateStartLocation(@RequestParam(value = "location", required = true) String location, Model model) { 
     //Perform your logic to update Start Location 
     return location; 
    } 
這個請求