2016-06-28 34 views
0

我在JSP中使用JavaScript。我可以通過<form action>發送formData到Spring Controller,但我現在需要通過Ajax發送。我沒有使用JQuery或AngularJS或任何其他JS框架。這裏使用JavaScript將formdata發送到Spring MVC Ajax

我的格式是:

<form:form id="saveAddressForm" modelAttribute="address"> 
    <tr> 
     <td><label>Address1</label></td> 
     <td><input type="text" name="addressLine1"></td> 
     <td><label>Address2</label></td> 
     <td><input type="text" name="addressLine2"></td> 
    </tr> 
    <tr> 
     <td><label>LandMark</label></td> 
     <td><input type="text" name="londMark"></td> 
     <td><label>City</label></td> 
     <td><input type="text" name="city"></td> 
    </tr> 
    <tr> 
     <td><label>Pincode</label></td> 
     <td><input type="number" name="pincode"></td> 
     <td></td> 
     <td><input type="submit" value="Save Addess" onsubmit="saveAddress()"></td> 
    </tr> 
</form:form> 

JS功能:

function saveAddress(){ 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
    if (xhttp.readyState == 4 && xhttp.status == 200) { 
     // On success i need to display a message. 
    } 
    }; 
xhttp.open("POST", "add_address.html", true); 
xhttp.send();} 

這裏,不包括在請求我FORMDATA即地址對象。

@RequestMapping(value = "/add_address", method = RequestMethod.POST) 
public String addAddress(@ModelAttribute("address") Address address, Model map) 
{ 

    // Services will be called here. 
    return null; 
} 

我想,我錯過了一些東西來添加我的對象來請求。

我看到幾篇SOF文章,他們用JQuery或AngularJS解決。我不知道這些。

編輯

思考如何提高我的問題。 我想要「modelAttribute」發送給控制器。不是單個參數也不是通過JS框架的作品。

回答

0

是什麼問題?

您需要添加參數來構建Adress對象。

Send POST data using XMLHttpRequest

+0

我的目標不是要控制層 – CHowdappaM

+0

檢查你的servlet映射,如果是看OK刪除'@ModelAttribute(「地址」)地址address',如果你在你的控制器通過。 –

0

您可以使用jQuery來輕鬆序列化表單數據,並要求通過。

這裏是jQuery的修改後的代碼。

function saveAddress(){ 
    var xhttp = new XMLHttpRequest(); 
    var form = document.getElementById('saveAddressForm'); 
    var data = new FormData(form); 
    xhttp.onreadystatechange = function() { 
    if (xhttp.readyState == 4 && xhttp.status == 200) { 
     // On success i need to display a message. 
    } 
    }; 
xhttp.open("POST", "add_address.html", true); 
xhttp.send(data);} 
+0

我沒有使用JQuery。 – CHowdappaM

+0

好的..我在這裏編輯了代碼,這是純粹的javascript –

+0

var data = new FormData(form);數據是否可以引用地址對象?在我的控制器中,我試圖獲得地址對象。不是個別的參數。可能?? – CHowdappaM

相關問題