JQuery发布JSON对象到服务器

我创build了一个需要张贴在运动衫,一个服务器运行的服务器,有一个REST的web服务得到传入的json对象,需要输出的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文件,在onload时运行这个方法

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

要发送json到服务器,你首先必须创buildjson

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

这是你将如何构造ajax请求发送json作为后var。

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

json现在将在json post var中。

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

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