簡體   English   中英

讀取從ASMX返回的JSON數據

[英]Reading the JSON data returned from 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);
        }
    }
}

我正在使用Newtonsoft.Json庫提供JsonConvert.SerializeObject功能。 當在Fiddler中調用或通過我的Jquery訪問時,我得到以下響應: 如在這種情況下在Google Chrome中看到的

此警報的代碼為:

$(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");
                }
            });
        });

而且,盡管我可以從msg.d 查看數據,但無法訪問它。 我想知道Response是什么。 我該怎么辦?

我並不完全相信我的ASMX將為所有工作返回正確的JSON類型。

有人可以幫忙嗎? :)

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

然后,您無需在JavaScript中進行雙重解碼。

反序列化的JSON對象似乎具有另一個JSON作為其值之一。 嘗試添加:

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

到您的成功回調,看看是否是這種情況。

更新:如果是這種情況,那么您已經對數據進行了兩次JSON編碼-請參閱C. Ross的答案以獲取適當的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM