I create a json that needs to be posted in jersey, a server running by grizzly that has a REST webservice gets incoming json object which need to be outputed. I'm giving a try but not sure how to implement this correctly.
import java.io.IOException;
import java.io.InputStream;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
import javax.ws.rs.*;
@Path("/helloworld")
public class GetData {
@GET
@Consumes("application/json")
public String getResource() {
JSONObject obj = new JSONObject();
String result = obj.getString("name");
return result;
}
}
i have a html file that runs this method while onload
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: 'application/json',
data: {
name:"Bob",
},
dataType: 'json'
});
alert("json posted!");
};
How to use POST method to send data in jQuery Ajax? The jQuery.post ( url, [data], [callback], [type] ) method loads a page from the server using a POST HTTP request. data − This optional parameter represents key/value pairs or the return value of the .serialize () function that will be sent to the server.
In this tutorial you will learn how to send and receive data from a web server through Ajax via HTTP GET or POST methods using jQuery. The jQuery's $.get () and $.post () methods provide simple tools to send and retrieve data asynchronously from a web server.
POST requests are identical to GET requests in jQuery. So, generally which method you should use either $.get () or $.post () is basically depends on the requirements of your server-side code. If you have large amount of data to be transmitted (e.g. form data) you need to use POST, because GET has a stringent limit on the data transfer.
.send () – This method send AJAX request. It is also used to send data. application/x-www-form-urlencoded; charset=UTF-8 is a default Content-Type but you can use any other type e.g. – application/json , multipart/form-data, etc. loadEmployees () – This function calls on page successfully loaded. Create object of XMLHttpRequest.
To send json to the server, you first have to create json
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
name:"Bob",
...
}),
dataType: 'json'
});
}
This is how you would structure the ajax request to send the json as a post var.
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
data: { json: JSON.stringify({
name:"Bob",
...
})},
dataType: 'json'
});
}
The json will now be in the json
post var.
It is also possible to use FormData()
. But you need to set contentType
as false
:
var data = new FormData();
data.append('name', 'Bob');
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: false,
data: data,
dataType: 'json'
});
}
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