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!"); };
To post JSON data to the server, we need to use the HTTP POST request method and set the correct MIME type for the body. The correct MIME type for JSON is application/json. In this POST JSON example, the Content-Type: application/json request header specifies the media type for the resource in the body.
Now lets see how we can send JSON objects list as given below: var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3, name:"atin"},{id:1, name:"puneet"}]; jQuery. ajax({ url: , type: "POST", data: {students: JSON. stringify(jsonObjects) }, dataType: "json", beforeSend: function(x) { if (x && x.
Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.
How do I post JSON data using JavaScript? To post data in JSON format using JavaScript/jQuery, you need to stringify your JavaScript object using the JSON. stringify() method and provide a Content-Type: application/json header with your request.
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