2013-10-17 196 views
0

我想打一個Ajax獲得來電server.Till現在我總是習慣:從Javascript將數據發送到Servlet的

$.get("/FruitResults?fruit="+fruitname+"&color="+colorname,function(data){addToTables(data);},"text"); 

發送參數水果,color.Now如果我有許多水果,它們的顏色,價格..

{apple:{color:red,price:30},orange:{color:orange,price:10}} 

和這麼大的水果名單,我怎麼把這個發送到servlet使用Ajax調用,以什麼格式?並且在servlet方面,我應該如何從請求對象中檢索請求參數?

回答

2

http get方法不適合發送複雜數據。因此,您必須使用post方法將複雜的數據從客戶端發送到服務器。你可以使用JSON格式來編碼這些數據。示例代碼如下:

var fruits = {apple:{color:red,price:30},orange:{color:orange,price:10}}; 
$.post("/FruitResults", JSON.stringify(fruits), function(response) { 
    // handle response from your servlet. 
}); 

注意,因爲您使用的post方法,你必須處理在servlet的doPost法代替doGet此請求。要檢索發佈的數據如下,你必須閱讀servlet請求的輸入流:

public void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 

    String jsonString = new String(); // this is your data sent from client 
    try { 
    String line = ""; 
    BufferedReader reader = request.getReader(); 
    while ((line = reader.readLine()) != null) 
     jsonString += line; 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 

    // you can handle jsonString by parsing it to a Java object. 
    // For this purpose, you can use one of the Json-Java parsers like gson**. 
} 

**鏈接GSONhttp://code.google.com/p/google-gson/