Possible Duplicate:
How to use Servlets and Ajax?
I am using the following code in Javascript to makes an Ajax call:
function getPersonDataFromServer() {
$.ajax({
type: "POST",
timeout: 30000,
url: "SearchPerson.aspx/PersonSearch",
data: "{ 'fNamn' : '" + stringData + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
}
});
}
I would like to do this in Java as well. Basically, I would like to write a Java client application which send this data via Ajax calls to the server.
How do I do Ajax in Java?
Code Example – How to Make AJAX Calls with Java Spring MVC. Step 1: Get JQuery Library. Download JQuery library and place it in JS folder within one of your web assets folder. Even simpler, include following ... Step 2: Create a Form. Step 3: Create AJAX Code. Step 4: Create Server-side Code.
Approach 2: In this approach, we will use jQuery to make an ajax call. The ajax () method is used in jQuery to make ajax calls. It is used as a replacement for all approaches which are not working to make ajax calls. $.ajax ( {arg1: value, arg2: value, ...
AJAX is no different from any other HTTP call. You can basically POST the same URL from Java and it shouldn't matter as far as the target server is concerned:
To create ajax example, you need to use any server-side language e.g. Servlet, JSP, PHP, ASP.Net etc. Here we are using JSP for generating the server-side code.
AJAX is no different from any other HTTP call. You can basically POST the same URL from Java and it shouldn't matter as far as the target server is concerned:
final URL url = new URL("http://localhost:8080/SearchPerson.aspx/PersonSearch");
final URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.connect();
final OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(("{\"fNamn\": \"" + stringData + "\"}").getBytes("UTF-8"));
outputStream.flush();
final InputStream inputStream = urlConnection.getInputStream();
The code above is more or less equivalent to your jQuery AJAX call. Of course you have to replace localhost:8080
with the actual server name.
If you need more comprehensive solution, consider httpclient library and jackson for JSON marshalling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With