2011-11-30 129 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\"";