2012-09-05 75 views
0

如何從ajax.I調用非靜態void函數出錯。 這是Ajax代碼: -如何通過ajax調用void非靜態函數?

$('#button2 button').click(function() { 

       $.ajax({ 
       type: "POST", 
       url: "practiced_final.aspx/display", 
       data: "{}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       async: true, 
       cache: false, 
       success: function() 
       { 
       }, 
       error: function (a, b, c) { 
        alert(a + b + c); 
       } 
      }) 
           return false; 

      }); 

這是C#方法代碼:

 [WebMethod] 
protected void display() 
    { 

    HttpContext.Current.Response.Write("Hello"); 
    } 

這是錯誤信息: -

[object XMLHttpRequest]errorundefined 

什麼,我缺少什麼?

請幫忙。

謝謝。

+0

加屬性到你的方法'display'' [Webmethod]'。我不確定您的這種方法是否應該公開 – harry180

+0

我已經添加了它,但沒有粘貼在這裏。我仍然沒有工作。 檢查更新的代碼。 – user1627138

+0

看到這個[http://stackoverflow.com/questions/1360253/call-non-static-method-in-server-sideaspx-cs-from-client-side-use-javascript]相關問題哪個應該可以解決你的問題 –

回答

1

爲它工作,你的函數必須是靜態的,它應該是這樣的:

[Webmethod] 
public static void display() 
{ 
    HttpContext.Current.Response.Write("Hello"); 
} 

,如果你希望你的函數返回您應將其更改爲一個字符串:

[Webmethod] 
    public static string display() 
    { 
     return "Hello"; 
    } 
+0

它仍然給出錯誤: - [object XMLHttpRequest] parsererrorundefined – user1627138

+0

你會得到一個JS錯誤? – kleinohad

+0

也許是因爲你返回的東西不是JSON。 – Stilgar

相關問題