2013-08-04 65 views
0

我寫這個java腳本來發送json對象到c#web服務。但它不工作...爲什麼? 這是我的JavaScript ..如何發送json對象到C#web服務器

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery- 1.5.1.js"></script> 

<script type="text/javascript"> 
    function BindJson() { 

document.getElementById("demo").innerHTML=Date(); 
     $.ajax({ 
      type: "POST", 
      url: "Service1.asmx/SerializeJson", 
      data: JSON.stringify({ person:{ firstName: "Denny" }}), 

      contentType: "application/json; charset=utf-8", 
      dataType: "json", 

      success: function (data2) { 
       alert(data2.d); 
      }, 
      error: function (request, status, errorThrown) { 
       alert(status); 
      } 
     }); 
    } 
</script> 

這是我的服務器類..

[System.Web.Script.Services.ScriptService] 
public class Service1 : System.Web.Services.WebService 
{ 
    [WebMethod] 
    public string SerializeJson(Person person) 
    { 
     return "Success"; 
    } 
    public class Person 
    { 
     public string firstName { get; set; } 
    } 
} 

回答

0

data.ajax選項需要一個名稱值對字符串或對象

data: { "myjson": JSON.stringify({ person:{ firstName: "Denny" }}) }, 
//OR 
data: "myjson="+JSON.stringify({ person:{ firstName: "Denny" }}), 
//Or just send the data values and retrieve in the way you get GET or POST variables in C# 
data: { person:{ firstName: "Denny" }}, 
1

您不應該使用JSON.stringify,因爲當您指定JSON的內容類型時,jQuery將使用JSON.stringify將其轉換。

 data: JSON.stringify({ person:{ firstName: "Denny" }}), 

     contentType: "application/json; charset=utf-8", 
     dataType: "json", 

將其更改爲

 data: { person:{ firstName: "Denny" }}, 

     contentType: "application/json; charset=utf-8", 
     dataType: "json", 

而且你不需要,除非它需要發送者爲對象的成員。

 data: { firstName: "Denny"}, 

     contentType: "application/json; charset=utf-8", 
     dataType: "json",