开发者

Reading the JSON data returned from ASMX

I have written an ASMX service that looks like thus;

namespace AtomicService
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class Validation : WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string IsEmailValid(string email)
        {
            Dictionary<string, string> response = new Dictionary<string, string>();
            response.Add("Response", AtomicCore.Validation.CheckEmail(email).ToString());
            return JsonConvert.SerializeObject(response, Formatting.Indented);
        }
    }
}

I'm using the Newtonsoft.Json library to provide the JsonConvert.SerializeObject functionality. When call in Fiddle开发者_JS百科r or accessed via my Jquery, I get this response:

Reading the JSON data returned from ASMX

The code for this alert is:

$(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "http://127.0.0.1/AtomicService/Validation.asmx/IsEmailValid",
                data: "{'email':'dooburt@gmail.com'}",
                contentType: "application/json",
                dataType: "json",
                success: function (msg) {
                    if (msg["d"].length > 0) {
                        alert("fish");
                    }
                    alert("success: " + msg.d);
                },
                error: function (msg) {
                    alert("error");
                }
            });
        });

And although I can see the data from the msg.d, I can't access it. I want to know what the Response is. How can I get at it?

I'm not entirely convinced my ASMX is returning the right type of JSON for this to all work.

Can anyone help? :)


@rsp's answer is technically correct, but the real problem is that you're doubly encoding your values in your asmx page.

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] //This will cause the response to be in JSON
    public Dictionary<string, string> IsEmailValid(string email)
    {
        Dictionary<string, string> response = new Dictionary<string, string>();
        response.Add("Response", AtomicCore.Validation.CheckEmail(email).ToString());
        return response; //Trust ASP.NET to do the formatting here
    }

Then you don't need to double decode in the JavaScript.


Your deserialized JSON object seems to have another JSON as one of its values. Try adding:

var data = $.parseJSON(msg.d);
alert(data.Response);

to your success callback to see if that's the case.

UPDATE: If that's the case then you have JSON-encoded your data twice – see the answer by C. Ross for a proper solution.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜