Quick Reference
1.1 In HTML, use jQuery
$.ajax()
to send a form request.
jQuery(document).ready(function($) { $("#search-form").submit(function(event) { // Prevent the form from submitting via the browser. event.preventDefault(); searchViaAjax(); }); }); function searchAjax() { var data = {} data["query"] = $("#query").val(); $.ajax({ type : "POST", contentType : "application/json", url : "${home}search/api/getSearchResult", data : JSON.stringify(data), dataType : 'json', timeout : 100000, success : function(data) { console.log("SUCCESS: ", data); display(data); }, error : function(e) { console.log("ERROR: ", e); display(e); }, done : function(e) { console.log("DONE"); } }); }
1.2 Spring controller to handle the Ajax request.
@Controller public class AjaxController { @ResponseBody @RequestMapping(value = "/search/api/getSearchResult") public AjaxResponseBody getSearchResultViaAjax(@RequestBody SearchCriteria search) { AjaxResponseBody result = new AjaxResponseBody(); //logic return result; } }
HTTP Request: GETPOST
Two commonly used methods for a request-response between a client and server are: GET and POST.
- GET – Requests data from a specified resource
- POST – Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POST chapter.
Spring MVC AJAX Hello World Example – Kiến thức cơ bản HTTP và AJAX
Bài đăng này đã không được cập nhật trong 2 năm
Khi tìm hiểu về giao thức HTTP mình có đọc 1 số bài hướng dẫn trả lời phỏng vấn về giao thức HTTP như:
Phương thức POST bảo mật hơn GET vì dữ liệu được gửi ngầm bằng mắt thường không thể nhìn thấy được
Phương thức GET luôn luôn nhanh hơn POST vì dữ liệu gửi đi được Browser giữ lại trong cache
Phương thức GET dữ liệu được gửi tường minh, chúng ta có thể thấy trên URL nên nó không bảo mật.
Các câu trả lời ở bên trên chưa chính xác là do bạn chưa hiểu đúng về giao thức HTTP
**Trong bài hướng dẫn này mình sẽ nói đến các vấn đề sau**
1) Các khái niệm cơ bản về giao thức HTTP (GET, POST)
2) Tạo 1 web application sử dụng Spring MVC với AJAX
Giao thức HTTP( Hyper Text Transfer Protocol) là gì ? HTTP là giao thức quy ước chung để cho 2 đối tượng A và B có thể giao thông ( giao tiếp ) với nhau. Cụ thể là giao tiếp với nhau bằng 1 định dạng sử dụng chữ (text)
Ta đã biết phép căn bản của phần mềm là 2 phép đọc (read) và ghi (write) dữ liệu (Phần mềm viết ra là để xử lý dữ liệu) – phép ghi còn tách ra làm 3 phép thêm, sửa, xóa. Khi người ta thiết kế ra giao thức HTTP cũng xoay quanh các phép căn bản này của phần mềm. Từ 4 phép căn bản này sẽ tạo ra 7 HTTP method:
- 4 phép đại diện cho đọc (read):
- GET
- Trace: đọc lỗi
- Option
- Head: đọc phần header
- 3 phép đại diện cho ghi (write):
- PUT
- POST
- DELETE
Nhưng trong quá trình làm việc chúng ta gần như chỉ sử dụng 1 phép đại diện cho đọc là GET, 1 phép đại diện cho ghi là POST. Từ đây dẫn đến sự khác nhau giữa GET và POST:
- Ví dụ A muốn gửi 1 thông điệp (message) rằng A muốn đọc dữ liệu (GET) của B, như vậy A không cần mang dữ liệu lên B. Nhưng khi A muốn gửi (POST) 1 bức ảnh đến B, A phải mang dữ liệu lên B. Như vậy GET đại diện cho phép đọc sẽ không có phần body mà chỉ có header, còn POST đại diện cho phép ghi sẽ có phần body (đưa dữ liệu vào body)
- Sự khác nhau giữa cấu trúc của GET và POST sẽ ảnh hưởng đến điểm mạnh điểm yếu của POST và GET.
-
GET sẽ
nhanh
hơn POST: GET sẽ đi nhanh hơn POST trong môi trường mạng vì nó k có body. Phần server khi xử lý message này sẽ nhanh hơn vì GET chỉ có header (khi nói đến
nhanh
ta phải nhắc đến 2 khía cạnh: traffic và performance) - Điểm mạnh của POST là đưa được data lên. Nếu muốn đưa 1 đoạn video, 1 bức ảnh GET sẽ k thể nào làm được => Nhưng vì GET đi nhanh hơn nên người ta có xu hướng dùng GET nhiều hơn, thế nên những dữ liệu mà mang lên server đủ nhỏ thì người ta có thể chuyển dữ liệu theo đường GET
- GET và POST đều có tính bảo mật như nhau, vì đối với GET ta có thể sử dụng kỹ thuật ajax để parametter k hiển thị lên trên url
**Tạo 1 project sử dụng Spring MVC + Ajax bằng maven, server chạy bằng jetty **
Ajax là gì ? Ajax là một khái niệm có thể mới lạ với những bạn newbie mới học lập trình web nên đôi lúc các bạn nghĩ nó là một ngôn ngữ lập trình mới. Nhưng thực tế không như vậy, ajax là một kỹ thuật viết tắt của chữ AJAX = Asynchronous JavaScript and XML, đây là một công nghệ giúp chung ta tạo ra những Web động mà hoàn toàn không reload lại trang nên rất mượt và đẹp. Đối với công nghệ web hiện nay thì ajax không thể thiếu, nó là một phần làm nên sự sinh động cho website
Các công nghệ sẽ sử dụng trong phần hg dẫn này:
- Spring 4.2.2.RELEASE
- Jackson 2.6.3
- Logback 1.1.3
- jQuery 1.10.2
- Maven 3
- JDK 1.8
- Tomcat 8 or Jetty 9
- Eclipse 4.5
- Boostrap 3
**Cấu trúc project **
**1)Project dependency: **
4.0.0
com.viblo
viblo-spring-learn-ajax
war
1.0-SNAPSHOT
viblo-spring-learn-ajax Maven Webapp
http://maven.apache.org
1.8
4.2.2.RELEASE
2.6.3
1.1.3
1.7.12
1.2
3.1.0
org.springframework
spring-webmvc
${spring.version}
commons-logging
commons-logging
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
javax.servlet
jstl
${jstl.version}
org.slf4j
jcl-over-slf4j
${jcl.slf4j.version}
ch.qos.logback
logback-classic
${logback.version}
javax.servlet
javax.servlet-api
${servletapi.version}
provided
viblo-spring-learn-ajax
org.apache.maven.plugins
maven-surefire-plugin
2.12.4
true
-Xmx2524m
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
1.8
UTF-8
true
-XDignore.symbol.file
org.eclipse.jetty
jetty-maven-plugin
9.3.0.M1
-Xmx2048m -Xms1536m -XX:PermSize=128m -XX:MaxPermSize=512m
manual
lib
${basedir}/target/viblo-spring-learn-ajax/WEB-INF/lib
8080
60000
${basedir}/src/main/webapp
${basedir}/src/main/webapp/WEB-INF/web.xml
${basedir}/target/classes
2)AjaxController AjaxController sẽ xử lý các ajax request từ phía client như thêm, hoặc tìm kiếm ! Sau đó trả về kết quả dưới dạng json cho client.
@Controller @RequestMapping("/home") public class AjaxController { private ListlistPerson = new ArrayList (); @RequestMapping(method = RequestMethod.GET) public ModelAndView home() { ModelAndView mv = new ModelAndView("web.home"); return mv; } @RequestMapping(value = "/addnew", method = RequestMethod.GET) public @ResponseBody String addNew(HttpServletRequest request) { String name = request.getParameter("name"); String age = request.getParameter("age"); Person person = new Person(name, Integer.parseInt(age)); listPerson.add(person); ObjectMapper mapper = new ObjectMapper(); String ajaxResponse = ""; try { ajaxResponse = mapper.writeValueAsString(person); } catch (JsonProcessingException e) { e.printStackTrace(); } return ajaxResponse; } @RequestMapping(value = "/search", method = RequestMethod.GET) public @ResponseBody String searchPerson(HttpServletRequest request) { String query = request.getParameter("name"); Person person = searchPersonByName(query); ObjectMapper mapper = new ObjectMapper(); String ajaxResponse = ""; try { ajaxResponse = mapper.writeValueAsString(person); } catch (JsonProcessingException e) { e.printStackTrace(); } return ajaxResponse; } public Person searchPersonByName(String query) { for (Person p : listPerson) { if (p.getName().equals(query)) { return p; } } return null; }
**3)Model Class ** Person class có nhiệm vụ đóng gói dữ liệu của người dùng nhập vào hoặc dữ liệu được trả về của server !
public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
**4)Jquery Ajax **
Trong file JSP, ta tạo 2 form thêm và tìm kiếm đơn giản gửi ajax request bằng
$.ajax
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Spring Ajax Example
Add New Person
Search Person by name
Spring MVC Ajax JSON Response Example
Name:
Age:
Running and Testing the Application
To run and test the application, follow these steps:
- Deploy the application on the Apache Tomcat server.
-
Open a web browser and navigate to
http://localhost:8080/spring-mvc-ajax-json-example/
. - The page should display the name and age retrieved from the Ajax request.
That’s it! You have successfully created a Spring MVC Ajax JSON response example.
Frequently Asked Questions
How to get JSON response in Ajax call using Spring MVC?
To get a JSON response in an AJAX call using Spring MVC, you can use the
@ResponseBody
annotation in your controller method. This will indicate to Spring that the method should return the response as JSON. You can then use jQuery’s
$.ajax()
method to make the AJAX call and handle the JSON response.
How to send JSON data to Spring MVC controller using AJAX?
To send JSON data to a Spring MVC controller using AJAX, you can use the
contentType
and
data
options in jQuery’s
$.ajax()
method. Set the
contentType
option to
'application/json'
and the
data
option to a JavaScript object representing the JSON data you want to send. Spring will automatically deserialize the JSON data into a Java object that can be used in your controller method.
How to return JSON data from Spring MVC controller?
To return JSON data from a Spring MVC controller, you can use the
@ResponseBody
annotation in your controller method. This will indicate to Spring that the method should return the response as JSON. You can then return a Java object that will be automatically serialized to JSON by Spring.
How to show data using AJAX in Spring MVC?
To show data using AJAX in Spring MVC, you can use jQuery’s
$.ajax()
method to make the AJAX call to your Spring controller. In the success callback function, you can then use jQuery’s DOM manipulation functions to update the HTML elements on your page with the data returned by the controller.
How to implement Ajax call in Spring security?
To implement an AJAX call in Spring Security, you will need to configure Spring Security to allow AJAX requests. You can do this by adding a CSRF token to your AJAX requests and configuring Spring Security to accept requests with the CSRF token. You can also configure Spring Security to return a JSON response for AJAX requests by using the
@ResponseBody
annotation in your controller methods.
How to use jQuery to make a REST API POST request in Spring MVC?
To use jQuery to make a REST API POST request in Spring MVC, you can use the
$.ajax()
method with the
type
option set to
'POST'
and the
url
option set to the URL of your REST API endpoint. You can then use the
data
option to specify the data you want to send in the POST request, and the
contentType
option to set the content type to
'application/json'
. In your Spring MVC controller, you can use the
@RequestBody
annotation to automatically deserialize the JSON data into a Java object.
Spring MVC: Ajax & JQuery
Today I want to demonstrate how to integrate AJAX into a Spring MVC application. I’m going to use JQuery on a client side for sending of requests and receiving of responses. This tutorial will be based on one of my previous tutorials about Spring MVC and REST services. In this article you will read how to make a web-application more interactive with the help of asynchronous requests.
Refactoring Spring MVC
2.1 Create a POJO to store the Ajax POST data.
public class HostingForm { private boolean display; private boolean cdn; private boolean hosting; private boolean paas; private String whoisPattern; private long id; private String domain; private String name; private String desc; private String tags; private String affLink; private String imageUrl; private String favUrl; //getters and setters
2.2 Accept the Ajax POST data with
@RequestBody
@RestController //... @RequestMapping(value = "/path-to/hosting/save", method = RequestMethod.POST) public String updateHosting(@RequestBody HostingForm hostingForm) { //... }
With
@RequestBody
, Spring will maps the POST data to
HostingForm
POJO (by name) automatically. Done.
You mat interest at this tutorial – Complete Spring 4 MVC + Ajax Form Post example
Spring Components
Only the important classes will be displayed.
4.1
@RestController
to handle the Ajax request. Read the comments for self-explanatory.
package com.mkyong.web.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; import com.mkyong.web.model.AjaxResponseBody; import com.mkyong.web.model.SearchCriteria; import com.mkyong.web.model.User; @RestController public class AjaxController { List
users; // @ResponseBody, not necessary, since class is annotated with @RestController // @RequestBody - Convert the json data into object (SearchCriteria) mapped by field name. // @JsonView(Views.Public.class) - Optional, filters json data to display. @JsonView(Views.Public.class) @RequestMapping(value = "/search/api/getSearchResult") public AjaxResponseBody getSearchResultViaAjax(@RequestBody SearchCriteria search) { AjaxResponseBody result = new AjaxResponseBody(); if (isValidSearchCriteria(search)) { List
users = findByUserNameOrEmail(search.getUsername(), search.getEmail()); if (users.size() > 0) { result.setCode("200"); result.setMsg(""); result.setResult(users); } else { result.setCode("204"); result.setMsg("No user!"); } } else { result.setCode("400"); result.setMsg("Search criteria is empty!"); } //AjaxResponseBody will be converted into json format and send back to the request. return result; } private boolean isValidSearchCriteria(SearchCriteria search) { boolean valid = true; if (search == null) { valid = false; } if ((StringUtils.isEmpty(search.getUsername())) && (StringUtils.isEmpty(search.getEmail()))) { valid = false; } return valid; } // Init some users for testing @PostConstruct private void iniDataForTesting() { users = new ArrayList
(); User user1 = new User("mkyong", "pass123", "[email protected]", "012-1234567", "address 123"); User user2 = new User("yflow", "pass456", "[email protected]", "016-7654321", "address 456"); User user3 = new User("laplap", "pass789", "[email protected]", "012-111111", "address 789"); users.add(user1); users.add(user2); users.add(user3); } // Simulate the search function private List
findByUserNameOrEmail(String username, String email) { List
result = new ArrayList
(); for (User user : users) { if ((!StringUtils.isEmpty(username)) && (!StringUtils.isEmpty(email))) { if (username.equals(user.getUsername()) && email.equals(user.getEmail())) { result.add(user); continue; } else { continue; } } if (!StringUtils.isEmpty(username)) { if (username.equals(user.getUsername())) { result.add(user); continue; } } if (!StringUtils.isEmpty(email)) { if (email.equals(user.getEmail())) { result.add(user); continue; } } } return result; } }
4.2 The “json data” will be converted into this object, via
@RequestBody
.
package com.mkyong.web.model; public class SearchCriteria { String username; String email; //getters and setters }
4.2 Create a dummy class for
@JsonView
, to control what should be returned back to the request.
package com.mkyong.web.jsonview; public class Views { public static class Public {} }
4.3 User object for search function. Fields which annotated with
@JsonView
will be displayed.
package com.mkyong.web.model; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; public class User { @JsonView(Views.Public.class) String username; String password; @JsonView(Views.Public.class) String email; @JsonView(Views.Public.class) String phone; String address; //getters, setters and contructors }
4.4 This object will be converted into json format and return back to the request.
package com.mkyong.web.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; public class AjaxResponseBody { @JsonView(Views.Public.class) String msg; @JsonView(Views.Public.class) String code; @JsonView(Views.Public.class) List
result; //getters and setters }
The
@JsonViewbelongs to Jackson library, not Spring framework.
Preparations
I need to modify the SmartphoneController class by removing methods which are not required any more. This is a first step of AJAX integration.
//imports are omitted @Controller @RequestMapping(value="/smartphones") public class SmartphoneController { @Autowired private SmartphoneService smartphoneService; @RequestMapping(value="/create", method=RequestMethod.GET) public ModelAndView createSmartphonePage() { ModelAndView mav = new ModelAndView("phones/new-phone"); mav.addObject("sPhone", new Smartphone()); return mav; } @RequestMapping(value="/create", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Smartphone createSmartphone(@RequestBody Smartphone smartphone) { return smartphoneService.create(smartphone); } @RequestMapping(value="/edit/{id}", method=RequestMethod.GET) public ModelAndView editSmartphonePage(@PathVariable int id) { ModelAndView mav = new ModelAndView("phones/edit-phone"); Smartphone smartphone = smartphoneService.get(id); mav.addObject("sPhone", smartphone); return mav; } @RequestMapping(value="/edit/{id}", method=RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Smartphone editSmartphone(@PathVariable int id, @RequestBody Smartphone smartphone) { smartphone.setId(id); return smartphoneService.update(smartphone); } @RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Smartphone deleteSmartphone(@PathVariable int id) { return smartphoneService.delete(id); } @RequestMapping(value="", method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public List< Smartphone > allPhones() { return smartphoneService.getAll(); } @RequestMapping(value="", method=RequestMethod.GET) public ModelAndView allPhonesPage() { ModelAndView mav = new ModelAndView("phones/all-phones"); List< Smartphone > smartphones = new ArrayList< Smartphone >(); smartphones.addAll(allPhones()); mav.addObject("smartphones", smartphones); return mav; } }
You can compare the new version of the SmartphoneController with the older one. Methods which process PUT, POST, DELETE requests and return ModelAndView objects were removed. The methods were deleted because AJAX calls can be addressed directly to REST methods. Now the controller contains just two types of methods:
- The first type directs user to pages where CRUD operations can be performed.
- The second type performs CRUD operations (REST methods)
Project Dependencies
4.0.0
com.mkyong
spring4-mvc-maven-ajax-example
war
1.0-SNAPSHOT
spring4 mvc maven ajax example
1.8
4.2.2.RELEASE
2.6.3
1.1.3
1.7.12
1.2
3.1.0
org.springframework
spring-webmvc
${spring.version}
commons-logging
commons-logging
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
javax.servlet
jstl
${jstl.version}
org.slf4j
jcl-over-slf4j
${jcl.slf4j.version}
ch.qos.logback
logback-classic
${logback.version}
javax.servlet
javax.servlet-api
${servletapi.version}
provided
org.apache.maven.plugins
maven-compiler-plugin
3.3
${jdk.version}
${jdk.version}
org.eclipse.jetty
jetty-maven-plugin
9.2.11.v20150529
10
/spring4ajax
org.apache.maven.plugins
maven-eclipse-plugin
2.10
true
true
2.0
spring4ajax
org.apache.maven.plugins
maven-war-plugin
2.6
false
org.wildfly.plugins
wildfly-maven-plugin
1.1.0.Alpha5
127.0.0.1
9990
admin
admin
spring4ajax.war
jQuery $.get() Method
The
$.get()
method requests data from the server with an HTTP GET request.
Syntax:
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the
$.get()
method to retrieve data from a file on
the server:
Example
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The first parameter of
$.get()
is the URL we wish to request ("demo_test.asp").
The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test.asp"):
response.write("This is some text from an external ASP file.")
%>
jQuery $.post() Method
The
$.post()
method requests data from the server using an HTTP POST request.
Syntax:
The required URL parameter specifies the URL you wish to request.
The optional data parameter specifies some data to send along with the request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the
$.post()
method to send some data along with the
request:
Example
$.post("demo_test_post.asp",
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The first parameter of
$.post()
is the URL we wish to request ("demo_test_post.asp").
Then we pass in some data to send along with the request (name and city).
The ASP script in "demo_test_post.asp" reads the parameters, processes them, and returns a result.
The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test_post.asp"):
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>
Spring MVC server site POST methods example
In this section simple Spring backend that handle POST method requests is presented.
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class EchoPostController { @RequestMapping(value = "/examples/echo-message", method = RequestMethod.POST) @ResponseBody public String sendPostMessage(@RequestParam("message") String message) { return message; } }
AJAX helps you to load data in the background and display it on the webpage, without reloading the complete webpage. It provides a smoother user experience while you are working with paging, sorting or filtering features in FlexGrid. This topic describes how to bind a FlexGrid at client side using an AJAX call.
This topic comprises the following steps:
The following image shows how the FlexGrid appears after completing the steps above:
Back to Top
Sale.cs. For more information on how to add a new model, see Adding Controls.
Sale.csmodel. We are using Sale class to represent sales order data in the database. Each instance of Sale object will correspond to a record in the FlexGrid control.
Sale.cs |
Copy Code |
|
HomeController.csfrom the Controllers folder.
C# |
Copy Code |
|
Index.htmlfrom View/Home folder.
HTML |
Copy Code |
We'll bind data to the control on the client side using JavaScript to make an AJAX call to the Action created in the HomeController.cs file. When we bind the grid at client-side in the Load function below, instead of assigning the result data of AJAX call to FlexGrid itemSource property, we should update the sourceCollection of FlexGrid's collectionView at client-side to retain the server-side features of collectionView. We have also added a code check for any errors in date values of JSON data.
Index.htmlfile inside the Home folder and copy the following JavaScript code.
Index.html |
Copy Code |
Index.html |
Copy Code |
jQuery - AJAX get() and post() Methods
The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.
References
About Author
Comments
i sending formdata to controller class. in controller how to access these data?
$(“button#submitMDRtable”).click(function(){var data = [];var minAmt, maxAmt, type, minCap, maxCap;$(“table tbody tr”).each(function(index) {minAmt = $(this).find(‘.minAmt’).text();maxAmt = $(this).find(‘.maxAmt’).text();type = $(this).find(‘.type’).text();minCap = $(this).find(‘.minCap’).text();maxCap = $(this).find(‘.maxCap’).text();//alert(minAmt+”–“+maxAmt+”–“+type+”–“+minCap+”–“+maxCap)//—->Form validation goes heredata.push({minAmt: minAmt,maxAmt: maxAmt,type: type,minCap: minCap,maxCap: maxCap});});submitFormData(data);console.log(data);});
function submitFormData(formData) {var url= ‘/mdrcharges’;alert(url);$.ajax({type: ‘POST’,data: formData,cache: false,processData: false,contentType: false,beforeSend: beforeSendHandler,url: url,success: function(result){if(result.success == true) {$(‘.alert-success’).show();$(‘.alert-danger’).hide();$(“#successmsg”).html(result.msg);setTimeout(function() {$(“.alert-success”).alert(‘close’);}, 10000);} else {$(‘.alert-danger’).show();$(‘.alert-success’).hide();$(“#error”).html(result.msg);setTimeout(function() {$(“.alert-danger”).alert(‘close’);}, 10000);}}});}
OK. This is an easy example, and everyone saw it a hundred times. But tell us what do you will do if you have here is a JSON:
{“abc”:{“sr”:”ok”,”citi”:[{“id”:”c2″,”value”:”london”},{…}…,{…}]}}
etc ?
Just send a POST request, along with your JSON data.
Spring 4 MVC Ajax Hello World Example
In this tutorial, we will show you how to create a Spring MVC web project and submit a form via Ajax.
Technologies used :
- Spring 4.2.2.RELEASE
- Jackson 2.6.3
- Logback 1.1.3
- jQuery 1.10.2
- Maven 3
- JDK 1.8
- Tomcat 8 or Jetty 9
- Eclipse 4.5
- Boostrap 3
P.S If the Jackson library is found in the project classpath, Spring will use Jackson to handle the json data to / from object conversion automatically.
Try this – Spring Boot Ajax example
Common Issues and Solutions
Debugging Ajax Issues in Spring MVC
When working with Ajax requests in Spring MVC, it is common to encounter issues related to the request not being sent or received properly. Here are some common issues and solutions:
- Incorrect URL: Ensure that the URL in the Ajax request matches the URL in the Spring MVC controller. Check for any typos or missing slashes in the URL.
- Missing Request Parameters: Check if all the required request parameters are being sent in the Ajax request. Use the browser’s developer tools to inspect the request and response headers and data.
- Cross-Origin Resource Sharing (CORS): If the Ajax request is being sent from a different domain than the one hosting the Spring MVC application, then CORS restrictions may apply. Check if the server is configured to allow CORS requests.
Optimizing JSON Response
Sending JSON data in Spring MVC can be optimized to improve the performance of the application. Here are some tips to optimize the JSON response:
- Minimize the JSON payload: Only send the required data in the JSON response. Remove any unnecessary data to reduce the payload size.
- Use GZIP compression: Compress the JSON response using GZIP compression to reduce the payload size and improve the response time.
- Use caching: Cache the JSON response on the client-side or server-side to reduce the number of requests and improve the response time.
By following these tips, we can optimize the JSON response and improve the performance of the Spring MVC application.
jQuery Ajax
In JSP, create a simple search form and send the form request with jQuery
$.ajax
.
<%@page session="false"%> <%@taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Search Form
You just add new Person
" + "Name: " + data.name + "
" + "Age: " + data.age; $("#ajax-response").html(result); }, error : function(e) { console.log("ERROR: ", e); } }); } function searchViaAjax() { var name = $("#query").val(); $.ajax({ type : "GET", contentType : "application/json", url : "${home}home/search/", data : { name : name }, dataType : 'json', timeout : 100000, success : function(data) { console.log("SUCCESS: ", data); if (data != null) { var result = "
You just search Person: " + data.name + "
"; $("#ajax-response").html(result); } else { var result = "
No person found
"; $("#ajax-response").html(result); } }, error : function(e) { console.log("ERROR: ", e); } }); }