[英]Reading the JSON data returned from ASMX
I have written an ASMX service that looks like thus; 我编写了一个看起来像这样的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);
}
}
}
I'm using the Newtonsoft.Json library to provide the JsonConvert.SerializeObject functionality. 我正在使用Newtonsoft.Json库提供JsonConvert.SerializeObject功能。 When call in Fiddler or accessed via my Jquery, I get this response: 当在Fiddler中调用或通过我的Jquery访问时,我得到以下响应:
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. 而且,尽管我可以从msg.d
查看数据,但无法访问它。 I want to know what the Response
is. 我想知道Response
是什么。 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. 我并不完全相信我的ASMX将为所有工作返回正确的JSON类型。
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. @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
}
Then you don't need to double decode in the JavaScript. 然后,您无需在JavaScript中进行双重解码。
Your deserialized JSON object seems to have another JSON as one of its values. 反序列化的JSON对象似乎具有另一个JSON作为其值之一。 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. 更新:如果是这种情况,那么您已经对数据进行了两次JSON编码-请参阅C. Ross的答案以获取适当的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.