JQuery的后JSON对象到服务器

JQuery的后JSON对象到服务器

问题描述:

创建需要在球衣被张贴一个JSON,通过具有REST Web服务灰熊运行的服务器获取其需要被outputed传入的JSON对象。我正在尝试,但不知道如何正确实施。JQuery的后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;  
     }     

    } 

我有一个运行时的onload

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


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

此方法JSON发送到服务器一个HTML文件,你首先必须创建JSON

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

这是你会怎样构造发送json作为post var的ajax请求。

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

的JSON现在将在json后变种。

+0

谢谢!我仍然在弄清楚服务器如何获得json对象。 – nihulus 2012-04-11 18:05:28

+0

以这种方式发送时,json将成为请求主体。如果您希望json在POST var中,则需要修改ajax请求。 – 2012-04-11 18:14:58

+0

但是如果我想要Json对象呢。即假设我有使用JSP的JSONObject创建,并希望传递给下一个页面,然后如何在jQuery的POST – 2013-08-02 09:33:29

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

var data = new FormData(); 
data.append('name', 'Bob'); 

function sendData() { 
    $.ajax({ 
     url: '/helloworld', 
     type: 'POST', 
     contentType: false, 
     data: data, 
     dataType: 'json' 
    }); 
}