读取从ASMX返回的JSON数据

doo*_*urt 1 c# jquery json asmx

我写了一个看起来像这样的ASMX服务;

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Newtonsoft.Json库来提供JsonConvert.SerializeObject功能.当在Fiddler中调用或通过我的Jquery访问时,我收到此响应: 正如在这种情况下谷歌浏览器中看到的那样

此警报的代码是:

$(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");
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

虽然我可以看到来自的数据,但msg.d我无法访问它.我想知道它Response是什么.我怎么能得到它?

我并不完全相信我的ASMX正在为所有工作返回正确类型的JSON.

有人可以帮忙吗?:)

C. *_*oss 5

@ rsp的答案在技术上是正确的,但真正的问题是你在asmx页面中对你的值进行了双重编码.

    [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
    }
Run Code Online (Sandbox Code Playgroud)

然后你不需要在JavaScript中进行双重解码.