JQuery post JSON object to a server

jquery, json

Solution

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.

Problem

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!"); }; ```

Original source