2012-08-08 51 views
1

我在我的應用中使用ajax,並且我必須使用$.post方法。如何在C#中發佈數據?

通常,發送到服務器的數據是鍵值對。我可以讓他們通過:

HttpContext.Current.Request.QueryPara['name']; 
.... 

但在某些情況下,要發送到服務器的數據不包含名稱。

它只是一個xml段。

像這樣:

var data='<data>xxxxx<data>'; 
$.post('http://server/service.asmx/test',data,function(){ 
    //callback 
},'xml'); 

那麼如何我可以在我的webmethod獲得數據?

回答

0

您應該使用'json'dataType將數據傳遞給web方法。

看一看樣品:

Service.asmx


[ScriptService] 
[WebService(Namespace = "http://localhost/testapp/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
public class Service : System.Web.Services.WebService{ 
    [WebMethod] 
    public int Square(int no){ return no * no;} 
} 

和JavaScript代碼來請求該的WebMethod

<script type="text/javascript"> 
$(function() { 
    $("#button1").click(function() { 
     $.ajax({ 
      type: "post", 
      url: "service.asmx/Square", 
      data: "{no: 10}", 
      dataType: "json", 
      contentType: "application/json", 
      success: function (data) { 
       alert("Result :" + data.d); 
      }, 
      error: function (src,type,msg) { 
       alert(msg); //open JavaScript console for detailed exception cause 
      } 
     }); 
    }); 
}); 
</script> 

<body> 
    <input type="button" id="button1" value="Square" /> 
</body> 
+0

我的意思是獲得服務器端的數據訪問服務器

var data= { data: '<data>xxxxx<data>'}; $.post('http://server/service.asmx/test',data,function(){ //callback },'xml'); 

然後:但你總是可以提供這樣的名字 – hguser 2012-08-08 03:18:46

0

我不知道,如果ASP。網可以做到這一點。你可以通過

var data = Request.Params("data");