2014-01-18 30 views
10

我不是jQuery的專家,考慮我更新鮮。這裏是我的代碼,它不負責由Request Body提交jQuery JSON數據。如何在jQuery中通過Request Body提交JSON數據?

<!doctype html> 
<html lang="en"> 
<head> 
    <title>jQuery Data submitted by JSON Body Request</title> 
    <script type="text/javascript" src="jquery-1.3.2.js"></script> 
    <script type="text/javascript"> 
    $.ajax({ 
     url : "/", 
     type: "POST", 
     data: [ 
      {id: 1, name: "Shahed"}, 
      {id: 2, name: "Hossain"} 
     ], 
     contentType: "application/json; charset=utf-8", 
     dataType : "json", 
     success : function(){ 
      console.log("Pure jQuery Pure JS object"); 
     } 
    }); 

    </script> 
</head> 
<body> 
    <p> 
     Example of submission JS Object by JSON Body Request<br/> 
     Its could submitted mass amount of data by Message body<br/> 
     It's secured and faster than any data submission . 
    </p> 
</body> 
</html> 

源後出現了:

Shahed=undefined&Hossain=undefined 

但所需的帖子來源是:

[{"id":1,"name":"Shahed"},{"id":2,"name":"Hossain"}] 

如何獲取所需的源後爲每個請求的身體?

+0

問題不清 –

+1

首先,您必須實際提交json數據而不是對象。 –

+0

如果您熟悉firebug調試器,那麼您將在控制檯的所有選項卡中看到每個請求。你會在哪裏得到Post Source。 Firebug控制檯負責在'Post Source'上顯示有效的'JSON''請求''Body' –

回答

17

這裏是你想要的輸出正確的代碼。

$.ajax({ 
     url : "/", 
     type: "POST", 
     data: JSON.stringify([ 
      {id: 1, name: "Shahed"}, 
      {id: 2, name: "Hossain"} 
     ]), 
     contentType: "application/json; charset=utf-8", 
     dataType : "json", 
     success : function(){ 
      console.log("Pure jQuery Pure JS object"); 
     } 
    }); 

你必須JS對象轉換爲字符串和JSON.stringify(JSObject)負責的方法。

相關問題