2012-04-11 66 views
35

創建需要在球衣被張貼一個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!"); 
     }; 

回答

64

此方法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

0

也可以使用FormData()。但是您需要將contentType設置爲false

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

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