2011-11-30 45 views
2

如果有人能指出這裏有什麼問題,我一定會很感激。我可以在webmethod中設置一個斷點,它會被擊中,但總是出錯。jQuery ajax json webservice錯誤

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAX_Test._Default" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
     <title>AJAX Test</title> 
     <script src="Scripts/jquery-1.7.min.js" type="text/javascript"></script> 
    </head> 
    <body> 
     <form id="form1" runat="server"> 
      <button id="theButton">Click Here</button> 
     </form> 
     <script type="text/javascript"> 
      $(function() { 
       $("#theButton").on("click", function() { 
        $.ajax({ 
         type: "POST", 
         url: "AjaxWebService.asmx/HelloWorld", 
         contentType: "application/json; charset=utf-8", 
         dataType: "json", 
         data: "{}", 
         success: AjaxSucceeded, 
         error: AjaxFailed 
        }); 
       }); 
      }); 

      function AjaxSucceeded(data, status) { 
       alert("success"); 
      } 

      function AjaxFailed(jqXHR, textStatus, errorThrown) { 
       alert(errorThrown); 
      } 
     </script> 
    </body> 
</html> 

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.Services; 

namespace AJAX_Test 
{ 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 

    public class AjaxWebService : System.Web.Services.WebService 
    { 
     [WebMethod] 
     public string HelloWorld() 
     { 
      return "Hello World"; 
     } 
    } 
} 
+1

什麼是錯誤? – jrummell

+0

有什麼錯誤? – MilkyWayJoe

+0

我更改了代碼,現在第三個參數會引發內部服務器錯誤。我看到下面有一個涉及[ScriptService]的答案,我會看看這個。 –

回答

4

這裏是你的問題:

添加此屬性爲您服務:

[ScriptService] 

,並添加到您的方法:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 

當您連接到服務從JavaScript它必須有這些屬性。

+0

添加[ScriptService]修復它沒有[ScriptMethod ...任何想法爲什麼? –

+0

無論如何,多謝。我當然沒有找到缺失的部分。 –

+0

每個MSDN - 「ScriptMethodAttribute屬性是可選的(但是,可以從客戶端腳本調用的方法必須應用System.Web.Services.WebMethodAttribute屬性。)。如果未使用ScriptMethodAttribute標記方法,則方法將爲通過使用HTTP POST命令調用,響應將被序列化爲JSON,不能從腳本覆蓋此設置。「它看起來像默認情況下所做的那樣。每天學習一些東西,我總是使用這個屬性,猜測它是可選的。 – Etch

0

你告訴jquery期待JSON數據作爲ajax服務器的響應,但是你發送的是一個空字符串作爲響應。一個JSON字符串應該是"Hello World",服務器端代碼應該是:

return "\"Hello World\"";