2016-02-25 56 views
0

我想使用ajax提交表單並避免刷新頁面。我使用Spring和Jquery。在Spring MVC頁面中使用Ajax提交表單

有人如何通過ajax提交表單並使用控制器中的類來完成任務?

模型類是拍賣(一個我試圖提交):

public class Auction { 

    private int id; 
    private int userId; 
    private String dateStart; 
    private String dateEnd; 
    private double maxPrice; 
    private boolean payed; 
    private boolean delivered; 
    private boolean scheduledTaskParsed; 
    private SimpleRegisteredUser user; 
    private WantedProduct wantedProduct; 
    (...) 
} 

和WantedProduct類是

public class WantedProduct { 
    private int id; 
    private String title; 
    private String description; 
    private int userId; 
    private int productStateId; 
    private String stateDescription; 
    private int productTypeId; 
    private String brand; 
    private String brandURL; 
    (...) 
} 

形式提交是:

<form:form id="new-auction" modelAttribute="auction" action="/product/create/" method="post" enctype="multipart/form-data"> 
    <form:hidden path="id"/> 
    <form:input path="wantedProduct.title" id="title" maxlength="300" placeholder="${nameLabel}*"/> 
    <form:input id="uploadFile" path="wantedProduct.photosWantedProduct[0].photo.photoFile" type="file" accept="image/*"/> 
    <form:select id="productTypeSelect" path="wantedProduct.productTypeId" >                               
     <c:forEach var="t" items="${types}">                            
      <form:option value="${t.id}"> 
       <spring:message code="${t.description}"/> 
      </form:option> 
      </c:forEach>           
    </form:select>  
    <form:input path="wantedProduct.brand" id="brand" placeholder=""/>  
    <form:input path="maxPrice"/>             
    <form:input path="wantedProduct.description"/>  
    <form:select path="wantedProduct.productStateId" >                              
     <c:forEach var="state" items="${productStates}">                            
      <form:option value="${state.id}"> 
       <spring:message code="${state.description}"/> 
      </form:option> 
      </c:forEach>           
    </form:select>  

    (...) 
</form:form> 

謝謝

+2

檢查答案:[如何使用Servlets和Ajax?](http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax#answer-4113258) – Kapouter

回答

0

嘗試了很多解決方案後,我想通了。

首先我序列形式:

var formFields = $('*:not(.no-serialize)', '#new-auction').serialize(); 

然後我分析這個字符串在這樣一個數組轉換:

var fieldArray = convertToArray(formFields); 

function getUrlVars(url,isInt) { 
    var hash; 
    var myJson = {}; 
    var hashes = url.slice(url.indexOf('?') + 1).split('&'); 
    for (var i = 0; i < hashes.length; i++) { 
     hash = hashes[i].split('='); 
     if(hash[0] !='language'){     
      myJson = processsField(hash[0],hash[1],myJson,isInt); 
     }   
    } 
    return myJson; 
} 

function processsField(key,value,myJson,isInt){ 

    if(key.indexOf('.')>0){ 
     keys = key.split('.'); 
     myJson[keys[0]] = processsField(keys[1],value,myJson[keys[0]],isInt); 
    } else{  
     if(myJson === undefined){ 
      myJson = {}; 
     } 
     myJson[key] = value.length>0?(isNaN(value) || isInt.indexOf(key) < 0 ?value.toString():Number(value)):null;  
    } 
    return myJson; 
} 

而且最後我稱之爲AJAX方法:

$.ajax({ 
        type: "POST", 
        global: false, 
        contentType : 'application/json; charset=utf-8', 
        //dataType: "text", 
        //dataType : 'json', 
        url: '${urlAddr}', 
        data: JSON.stringify(fieldArray), 
        success :function(result) {      
         console.log("yupii... Success");         
        }, 
        error: function(objRequest){  
         console.log("error"); 
         console.log(objRequest.responseText); 
        } 
       }); 

通過這種方式,控制器將類拍賣作爲輸入,一切都像魅力一樣工作!

謝謝你的一切!