小编典典

jQuery将JSON对象发布到服务器

json

我创建了一个需要发布到jersey的json,这是由grizzly运行的具有REST网络服务的服务器获取需要输出的传入json对象。我正在尝试,但不确定如何正确实施。

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;      
        }

    }

我有一个在加载时运行此方法的html文件

    function sendData() {
        $.ajax({
                url: '/helloworld',
                type: 'POST',
                contentType: 'application/json',
                data: {
                    name:"Bob",


                },
                dataType: 'json'
            });
            alert("json posted!");
        };

阅读 260

收藏
2020-07-27

共1个答案

小编典典

要将json发送到服务器,首先必须创建json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

这就是构造ajax请求以将json作为post var发送的方式。

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

json现在将在jsonpost var中。

2020-07-27