使用JQuery .ajax时,使用jquery’json’vs’text’时不会调用Success方法
我有一个ASP.Net网页试图使用jquery .axax方法从asmx webservice检索数据。 当dataType =“text”时,ajax方法正确调用成功方法,但是当使用“json”的dataType时,我无法返回它。 谁能看到我错过的东西? 我在http://weblogs.asp.net/jaredroberts/archive/2009/08/28/great-article-on-cascading-dropdown-list-and-jquery.aspx上在线获取’json’示例
客户:
function getText() { alert("getText"); $.ajax({ type: "POST", url: "test.asmx/HelloWorld", dataType: "text", success: function(response) { alert("text"); } }); } function getJson() { alert("getJson"); $.ajax({ type: "POST", url: "test.asmx/HelloWorld", contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { alert("json"); } }); }
Serverside Webservice电话:
[WebMethod] public string HelloWorld() { return "Hello World"; }
最后,我的问题的根源是类装饰缺少[ScriptService]属性。 我改为class声明:
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class SearchFilters : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return ""; } }
使用Fiddler我发现返回了以下错误消息:
只能从脚本中调用类定义中具有[ScriptService]属性的Web服务
你应该看看这篇文章。 假设你使用VB,这应该工作: 我如何在VB.NET中JSON编码数组?
您的调用失败,因为当您将数据类型声明为json
,jQuery期望JSON作为结果,但您返回Hello World
。 请尝试下面的代码,打印"Hello World"
,这是有效的JSON。
public string HelloWorld() { return """Hello World"""; }
这是我尝试过的,它完美地工作:
客户:
Serverside Webservice电话:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace WebApplication2 { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "{ \"message\":\"Hello World\" }"; } } }
确保您的webservice类上有[System.Web.Script.Services.ScriptService]
属性。
注意:在上面的示例中,返回的JSON是硬编码的,但是对于假设的人对象,您可以像下面一样轻松地将要返回的对象序列化为JSON:
Person p = new Person(); p.FirstName = "Bob"; p.LastName = "Smith"; p.Age = 33; p.Married = true; Microsoft.Web.Script.Serialization.JavaScriptSerializer jss = new Microsoft.Web.Script.Serialization.JavaScriptSerializer(); string serializedPerson = jss.Serialize(p);
您的类必须具有属性:[ScriptService]然后声明方法:
[WebMethod] public string GetSomeString() { return "SomeString"; }
当您尝试处理呼叫时:
function ShowString() { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "/YourService.asmx/GetSomeString" , data: "{}", dataType: "json", success: function (msg) { console.debug(msg); alert(msg.d); } });
会给你正确的输出你期待的“SomeString”。
-Raj