【问题标题】:using JQuery .ajax, a Success method is not called when using jquery 'json' vs 'text'使用 JQuery .ajax,使用 jquery 'json' vs 'text' 时不会调用 Success 方法
【发布时间】:2011-09-20 20:46:04
【问题描述】:

我有一个 ASP.Net 网页尝试使用 jquery .axax 方法从 asmx 网络服务中检索数据。当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"); }
    });
}

服务器端 Web 服务调用:

[WebMethod]
public string HelloWorld() {
    return "Hello World";
}

【问题讨论】:

  • 您需要对“hello world”进行 json 编码。

标签: jquery asp.net ajax json


【解决方案1】:

最后,我的问题的根源是类装饰中缺少 [ScriptService] 属性。我将班级声明改为:

[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 服务 可以从脚本调用定义

【讨论】:

    【解决方案2】:

    您的调用失败,因为当您将数据类型声明为 json 时,jQuery 期望 JSON 作为结果,但您返回 Hello World。请尝试使用下面的代码来打印 "Hello World",这是有效的 JSON。

    public string HelloWorld() {
        return """Hello World""";
    }
    

    【讨论】:

    • 对不起 - 我根本不了解 VB,并假设它支持转义功能,但它不支持。我已经修改了我的答案。
    • 其实这是c#,但是上面的还是不行。不过谢谢!
    【解决方案3】:

    这是我尝试过的,效果很好:

    客户:

    <script type="text/javascript">
        $(function () {
            $('#testbutton').click(function () {
                $.ajax({
                    type: "POST",
                    url: "WebService1.asmx/HelloWorld",
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    data: "{}",
                    dataType: "json",
                    success: function (data, status) {
                        var response = $.parseJSON(data.d);
                        alert(response.message);
                        alert(status);
                    },
                    error: function (xmlRequest) {
                        alert(xmlRequest.status + ' \n\r ' + xmlRequest.statusText + '\n\r' + xmlRequest.responseText);
                    }
                });            
            });
        });
    </script>
    

    服务器端 Web 服务调用:

    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\" }";
            }
        }
    }
    

    确保您的 Web 服务类具有 [System.Web.Script.Services.ScriptService] 属性。

    注意:在上面的示例中,返回的 JSON 是硬编码的,但您可以轻松地将要返回为 JSON 的对象序列化为假设的 person 对象,如下所示:

    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);
    

    【讨论】:

    • 恐怕这行不通,因为我在银行,所以无法加载 FF。但是我真的很想完成上面的文章正在做的事情,为什么这不起作用: public List GetCases() { List case = new List() { new Cases() { CaseName = “测试” } };返回 case.ToList(); }
    • (抱歉格式化)在上面的例子中,我通过'json'(和'text')调用'GetCases'webmethod,使用一个jquery调用GetCases。 GetCases 返回 List。然而,像上面一样,'text' 返回一个结果,但 'json' 'success' 方法永远不会触发。我是否从列出的 MS 文章中获取了一些信息?
    • @davewilliams459 您需要查看服务的响应是什么。您可以使用 Google Chrome,它具有与 Firebug 类似的工具,或者为 Internet Explorer 安装 Fiddler 并使用它来分析您的 ajax 请求。但首先,一定要查看发送的内容和返回的内容,以便进一步调试。
    • Grrrrrr... Chrome、FireFox 和 Fiddler 在银行受到限制。我得想办法。呸呸呸
    • @davewilliams459 如果您正在进行涉及 ajax 的 Web 开发,那么至少其中一种工具对于提高生产力至关重要。当我开始工作时,我会尝试从头开始创建您的解决方案,看看它是否有效,我会为您发送/发布一份工作副本。
    【解决方案4】:

    您的课程必须具有属性:[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”。

    -拉吉

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      相关资源
      最近更新 更多