2015-05-03 64 views
3

我試圖使用AJAX調用webmethod功能,但無法獲得適當的結果。我搜索了我的問題,發現了很多解決方案,但那些解決方案對我來說並不合適。請指導我做錯了什麼。幫助將不勝感激。ASP.NET 500內部服務器錯誤,同時從javascript調用webmethod

乾杯

代碼段

function checkUserNameExists() { 

//initialization 
var pagePath = window.location.pathname + "/getUsername"; 
var value = document.getElementById('control_userName').value; 
var dataString = "{ 'value':'" + value + "' }"; 
$.ajax({ 
    type: "GET", 
    url: pagePath, 
    data: dataString, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    error: 
      function (XMLHttpRequest, textStatus, errorThrown) { 

      }, 
    success: 
      function (result) { 
       var flag = true; 
       if (result != null) { 
        flag = result.d; 
        if (flag == "True") { 
         alert('okay fine you are good'); 
        } 
        else { 
         alert('try again'); 
        } 
       } 
      } 
}); 
} 

方法在代碼隱藏文件

[WebMethod] 
    [ScriptMethod(UseHttpGet = true)] 
    public string getUsername(string value) 
    { 
     return "True"; 
    } 

EXCEPTION

ExceptionType: "System.InvalidOperationException" 
    Message: "An attempt was made to call the method 'getUsername' using a  POST request, which is not allowed." 

回答

3

首先,將WebMethod是在頁面類,而不是在一個WebService類,那麼它應該是靜態的。

其次,傳輸的數據是不是一個真正的字符串,而是一個對象,因此將其更改爲:

var dataString = { 'value': value }; 

第三件事,「類型」是舊版本的jQuery,你要麼改變你的AJAX來電:

method: "GET", 
url: pagePath, 
data: dataString, 
contentType: "application/json; charset=utf-8", 
dataType: "json",... 

或改變功能在服務器端獲取後調用,通過移除

UseHttpGet = true 
+0

是該方法在頁面類中實現。我已經將它的簽名更改爲靜態,但仍然得到相同的錯誤。 - > GET http:// localhost:7492/route/frame_signup/signup.aspx/getUsername?abc 500(內部服務器錯誤) –

+0

您做了其他事情嗎? var dataString = {'value':value};而不是var dataString =「{'value':'」+ value +「'}」;? 你能在這裏發佈錯誤嗎? – ShaharB

+0

是的,我這是你上面提到的同樣的結果,但仍然是相同的結果。 –

2

也許你需要靜態添加到您的方法聲明如下

[WebMethod] 
[ScriptMethod(UseHttpGet = true)] 
public static string getUsername(string value) 
{ 
    return "True"; 
} 

如果不是這樣的話,你可以在F12瀏覽器的>網絡,然後點擊錯誤訊息,瞭解它簡單。

關於報告的問題,用GET請求的問題,儘量做到張貼

+0

我的控制檯顯示以下錯誤:GET http:// localhost:7492/route/frame_signup/signup.aspx/getUsername?abc 500(內部服務器錯誤) –

+0

是的,通過在F12控制檯打開期間單擊此錯誤,它會顯示錯誤的詳細信息..也可以嘗試從客戶端和服務器端函數中刪除參數,以檢查發送參數是否不是錯誤 –

+0

我編輯了我的問題併發布了異常。謝謝 –

2

答案在這裏:link

問題在於註釋我使用[ScriptMethod(UseHttpGet = true)]而導致錯誤。只需將值從true更改爲false即可。

相關問題