2014-06-19 181 views
0

我在我的代碼中有一個WebMethod,我通過AJAX調用。該方法在使用GET請求時有效,但我更願意使用POST,我也想知道爲什麼這不起作用和/或我做錯了什麼。由於GET請求不允許POST請求失敗

的JavaScript

$(document).ready(function() { 
     $.ajax({ 
      url: "Default.aspx/HelloWorld", 
      method: "POST", 
      data: "{}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (data) { 
       $("#test1").html(data.d); 
      }, 
      error: function (err) { 
       $("#errOutput").text("ERROR: " + err.responseText); 
      } 
     }); 
    }); 

C#

[WebMethod] 
    [ScriptMethod(UseHttpGet=false)] 
    public static string HelloWorld() 
    { 
     return "Hello World!"; 
    } 

錯誤

Message: 
"An attempt was made to call the method \u0027HelloWorld\u0027 using a 
GET request, which is not allowed.", 

StackTrace: 
"at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData 
methodData, HttpContext context)\r\n 
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext 
context, WebServiceMethodData methodData)", 

ExceptionType:"System.InvalidOperationException" 

回答

2

縱觀一些jQuery documentation我認爲你使用的是錯誤的屬性。我懷疑這一點:

method: "POST" 

應該

type: "POST" 

method感覺比較明智的名字對我來說太,但我們去...

(聲明:我從來沒有用過jQuery自己...這個答案純粹是基於文檔。)

+0

哇,我不能相信我錯過了。謝謝,喬恩! – ExceptionLimeCat

相關問題