使用JQuery .ajax时,使用jquery'json'vs'text'时不会调用Success方法

时间:2022-06-01 05:45:06

I have an ASP.Net web page attempting to retrieve data from an asmx webservice using the jquery .axax method. The ajax method correctly call a success method when the dataType = "text", however I cannot get it to return when using the dataType of "json". Can anyone see what I am missing? I am getting the 'json' example online at http://weblogs.asp.net/jaredroberts/archive/2009/08/28/great-article-on-cascading-dropdown-list-and-jquery.aspx

我有一个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'示例

Client:

客户:

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 Call:

Serverside Webservice电话:

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

5 个解决方案

#1


2  

In the end the source of my issue was the lack of the [ScriptService] attribute on the class decoration. I changed to class declartion to:

最后,我的问题的根源是类装饰缺少[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 "";
    }
}

Using Fiddler I discovered the following error message was returned:

使用Fiddler我发现返回了以下错误消息:

Only Web services with a [ScriptService] attribute on the class definition can be called from script

只能从脚本中调用类定义中具有[ScriptService]属性的Web服务

#2


1  

You should check out this other article. Assuming you are using VB, this should work: How can I JSON encode an array in VB.NET?

你应该看看这篇文章。假设你使用VB,这应该工作:我如何在VB.NET中JSON编码数组?

#3


1  

Your call fails because when you declare the datatype as json, jQuery is expecting JSON as a result, but you return Hello World. Try the code below, instead, to print "Hello World", which is valid JSON.

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

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

#4


1  

Here is what I tried and it worked perfectly:

这是我尝试过的,它完美地工作:

Client:

客户:

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

Serverside Webservice Call:

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

Make sure you have [System.Web.Script.Services.ScriptService] attribute on your webservice class.

确保您的webservice类上有[System.Web.Script.Services.ScriptService]属性。

NOTE: in the example above the returned JSON is hardcoded, but you can just as easily serialize the objects you want to return as JSON as follows for a hypothetical person object:

注意:在上面的示例中,返回的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);

#5


0  

Your class must be with attribute : [ScriptService] Then declare method:

您的类必须具有属性:[ScriptService]然后声明方法:

  [WebMethod]
    public string GetSomeString()
    {
        return "SomeString";
    }

When you are trying to handle call:

当您尝试处理呼叫时:

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

Will give you proper output what you are expecting "SomeString".

会给你正确的输出你期待的“SomeString”。

-Raj

-Raj

#1


2  

In the end the source of my issue was the lack of the [ScriptService] attribute on the class decoration. I changed to class declartion to:

最后,我的问题的根源是类装饰缺少[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 "";
    }
}

Using Fiddler I discovered the following error message was returned:

使用Fiddler我发现返回了以下错误消息:

Only Web services with a [ScriptService] attribute on the class definition can be called from script

只能从脚本中调用类定义中具有[ScriptService]属性的Web服务

#2


1  

You should check out this other article. Assuming you are using VB, this should work: How can I JSON encode an array in VB.NET?

你应该看看这篇文章。假设你使用VB,这应该工作:我如何在VB.NET中JSON编码数组?

#3


1  

Your call fails because when you declare the datatype as json, jQuery is expecting JSON as a result, but you return Hello World. Try the code below, instead, to print "Hello World", which is valid JSON.

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

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

#4


1  

Here is what I tried and it worked perfectly:

这是我尝试过的,它完美地工作:

Client:

客户:

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

Serverside Webservice Call:

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

Make sure you have [System.Web.Script.Services.ScriptService] attribute on your webservice class.

确保您的webservice类上有[System.Web.Script.Services.ScriptService]属性。

NOTE: in the example above the returned JSON is hardcoded, but you can just as easily serialize the objects you want to return as JSON as follows for a hypothetical person object:

注意:在上面的示例中,返回的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);

#5


0  

Your class must be with attribute : [ScriptService] Then declare method:

您的类必须具有属性:[ScriptService]然后声明方法:

  [WebMethod]
    public string GetSomeString()
    {
        return "SomeString";
    }

When you are trying to handle call:

当您尝试处理呼叫时:

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

Will give you proper output what you are expecting "SomeString".

会给你正确的输出你期待的“SomeString”。

-Raj

-Raj