开发者

using JQuery .ajax, a Success method is not called when using jquery 'json' vs 'text'

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 usi开发者_JAVA百科ng 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

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:

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


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:

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

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


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.

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


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:

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.

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:

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


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

  [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".

-Raj

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜