【问题标题】:JQuery post JSON object to a serverJQuery 将 JSON 对象发布到服务器
【发布时间】:2026-02-10 11:35:02
【问题描述】:

我创建了一个需要在 jersey 中发布的 json,由 grizzly 运行的具有 REST web 服务的服务器获取需要输出的传入 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!");
        };

【问题讨论】:

    标签: jquery json


    【解决方案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 现在将位于 json 帖子变量中。

    【讨论】:

    • 谢谢!我还在弄清楚服务器如何获取 json 对象。
    • 这样发送时,json就是请求体。如果您希望 json 位于 POST var 中,则需要修改 ajax 请求。
    • 但是如果我想要 Json 对象作为它呢。即假设我使用 jsp 创建了 JSONObject 并希望传递到下一页然后如何在 jquery POST 中发送 JSONObject (jsonobj)
    • @Optimus 两种方式都会在 post 请求中发送 jsonobject。第一个,jsonstring 将在 post 请求的请求正文中,第二个 jsonstring 将在名为“json”的 post 变量中
    • 只是因为你的身体解析器没有它就无法检测到。但事实并非如此。拥有它是个坏主意
    【解决方案2】:

    也可以使用FormData()。但是你需要将contentType设置为false

    var data = new FormData();
    data.append('name', 'Bob'); 
    
    function sendData() {
        $.ajax({
            url: '/helloworld',
            type: 'POST',
            contentType: false,
            data: data,
            dataType: 'json'
        });
    }
    

    【讨论】: