2011-03-09 143 views
1

我已经写了一个看起来像这样的ASMX服务;读取从ASMX返回的JSON数据

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功能。当小提琴手电话或通过我的Jquery的访问,我得到这样的回应: as seen in google chrome in this case

此警报的代码是:

$(document).ready(function() { 
      $.ajax({ 
       type: "POST", 
       url: "http://127.0.0.1/AtomicService/Validation.asmx/IsEmailValid", 
       data: "{'email':'[email protected]'}", 
       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。

任何人都可以帮忙吗? :)

回答

4

您的反序列化JSON对象似乎有另一个JSON作为其值之一。尝试添加:

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

您的成功回调,看看是否是这种情况。

更新:如果是这种情况,那么你有JSON编码你的数据两次 - 见the answer by C. Ross一个适当的解决方案。

+0

请参阅我的回答。 –

+0

@C。 Ross:你解决问题的速度比原来的海报要快,并验证双JSON编码是否确实是这里的问题。我会更新我的答案以引用您的答案。 – rsp

+0

这工作完美rsp!非常感谢。然而,我很好奇C.罗斯的回答,但你已经解决了我原来的问题。非常感谢:) – dooburt

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 
    } 

然后你不需要在JavaScript中加倍解码。

+0

感谢C. Ross的回复。我按照你的建议完成了(在return response中需要一个'.ToString()'),但是响应是对象类型为字符串,而不是对象本身。我曾与我以前的服务版本,并偶然发现一个博客,建议我序列化? – dooburt

+0

@dooburt研究,研究... –

+0

@dooburt [这个问题](http://stackoverflow.com/questions/1791088/asp-net-scriptmethod-generating-empty-json)将表明它确实做了序列化您。我不知道这是否与字典问题... –