2011-05-19 99 views
1

我下载了一些代码,并在它下面的代码片段:为什么我的post jQuery Ajax请求会使用JSON?

function GetCommentBySessionIDWCF_JSON() { 
      varType = "POST"; 
      varUrl = "service/CommentSessionIDWCFService.svc/GetCommentsByPost"; 
      varData = '{"SessionID": "' + '123' + '"}'; 
      varContentType = "application/json; charset=utf-8"; 
      varDataType = "json"; 
      varProcessData = true; 

      //now to do the clever stuff 
      $.ajax({ 
       type: varType, //GET or POST or PUT or DELETE verb 
       url: varUrl, // Location of the service 
       data: varData, //Data sent to server 
       contentType: varContentType, // content type sent to server 
       dataType: varDataType, //Expected data format from server 
       processdata: varProcessData, //True or False 
       success: function (data) {//On Successfull service call 

        $.each(data.GetCommentsByPostResult, function (e) { 
         alert(e.CommentText); 
        }); 

       }, 
       error: ServiceFailed// When Service call fails 
      }); 

什么即时知道是为什么我要在这则讯息发送JSON?我读了jQuery文档,它说:

“要发送到服务器的数据。它被转换为查询字符串,如果还不是字符串,它会附加到GET请求的url。为了防止这种自动处理,对象必须是键/值对,如果value是一个数组,则jQuery会根据传统设置的值(如下所述)使用相同的键序列化多个值。

但是,当我将'数据'中的JSON更改为字符串时,我得到一个400错误。为什么?

+0

应该只是可以将数据类型默认为字符串,如果您从该脚本中删除它。 – Marty 2011-05-19 08:34:22

+0

在您的ajax选项上设置dataType – Ibu 2011-05-19 08:38:43

回答

1

它不是JSON,它是一个包含键值对的对象,呈现给HTTP ?param=value以发送到服务器。

+0

仅适用于GET请求。他发送POST。 – 2011-05-19 08:33:44

+1

原理相同,查询字符串在URL上不可见。 – 2011-05-19 08:34:50

+0

啊我明白了,所以我想知道在post方案中的这种标准做法吗?所有帖子是否包含关键值对? – Exitos 2011-05-19 08:39:35