2013-03-11 60 views
0

我在網上看到了許多不同的答案,並做了大量的複製和粘貼。它只是不適合我。任何人都可以告訴我爲什麼? 我很沮喪> _ < 我必須在我的web.config文件上做些什麼嗎? 我不明白即使是我的「WebService.asmx/add」也不會從我的瀏覽器返回任何東西(因爲沒有這樣的鏈接。)jQuery如何得到任何結果?我必須添加一些httphandlers,對吧? enter image description here如何使用jQuery使用asmx web服務?

+0

請使用「在新選項卡中打開圖像」來放大圖像。 – 2013-03-11 15:40:21

+0

請編輯問題併發布代碼 – 2013-03-11 15:45:07

+0

如果您只是在瀏覽器窗口中打開相同的URL,該怎麼辦? – 2013-03-11 15:51:24

回答

1

正如我在您的圖像中看到的,您的webmethod沒有靜態方法。

webmethod應該是一個靜態方法,以便使用服務。 WebMethod and Static

[WebMethod] 
Public static string HelloWorld() 
{ 
return "Hi"; 
} 

請與該鏈接時經過了更多信息

  1. WebService and Jquery
+0

我加了靜態。 jQuery仍然不起作用。 並添加靜態後,WebService的不會列出靜態方法納入其業務列表 – 2013-03-11 16:21:51

+0

@Ravi:您提供的參考鏈接是用於添加靜態的WebMethod到頁面,而不是一個web服務。 – derloopkat 2013-09-28 13:51:47

0

我不知道我是否遭人恨還是什麼。沒有人會回答我。 非常傷心。 ......> _ < ... 後的研究裏,我發現了一些方式工作 屬性需要序列數據作爲JSON字符串是

[System.Web.Script.Services.ScriptService] 

,所以我有我的ASMX代碼

<%@ WebService Language="C#" Class="WebService" %> 

using System; 
using System.Web; 
using System.Web.Services; 
using System.Web.Services.Protocols; 
using System.Web.Script.Services; 
using System.Data; 
using System.Data.SqlClient; 
[System.Web.Script.Services.ScriptService] 
[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
public class WebService : System.Web.Services.WebService { 

[WebMethod]  
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string HelloWorld() { 
    return "Hello World"; 
} 
[WebMethod]  
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public int add(int a, int b) 
{ 
    return a + b; 
} 

}

我的jQuery代碼爲

 $(
     function() { 
      $.ajax({ 
       type: "POST", 
       url: 'WebService.asmx/add', 
       data: "{'a':15, 'b':20}", //be careful! do pass it as a string 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (msg) { 
        alert(msg.d); 
       }, 
       error: function (e) { 
        alert("WebSerivce unreachable"); 
       } 
      }); 
     } 
    ); 

其中正確返回35.

很好!

+0

PS:不要聲明靜態方法,它不會工作! – 2013-03-13 15:00:12