访问JSON字符串的一些元素

时间:2011-06-16 17:47:26

标签: jquery json

这就是我在代码背后所做的:

 [WebMethod]
[ScriptMethod(ResponseFormat =  ResponseFormat.Json)]

public static string CheckInsertRecord(String EventType, String BeginDate, String EndDate)
{
    NCDCPoint ncdc = new NCDCPoint();
    CEOSurveyDataContext CDC = new CEOSurveyDataContext();
    int et = Convert.ToInt32(EventType);
    CultureInfo provider = CultureInfo.InvariantCulture;
    DateTime b = Convert.ToDateTime(BeginDate);
    DateTime e = Convert.ToDateTime(EndDate);

   var query = (from n in CDC.NCDCPoints
                where n.EVENT_TYPE_ID == et && n.BeginDate == b && n.EndDate == e
                select new { 
                   n.EVENT_TYPE_ID,
              BeginDate =  n.BeginDate.ToString("yyyy-MM-dd",provider),
               EndDate = n.EndDate.ToString(),
                n.BeginLAT,
              BeginLONG =  n.BeginLONG,
                n.EndLAT,
                n.EndLONG});


   if (query.Any())
   {
       return new JavaScriptSerializer().Serialize(query.ToList());
   }
   else
   {
       return "No duplicate";
   }



}

所以我将此字符串发送回jquery。我试图只访问EVENT_TYPE_ID值。 所以,我尝试使用alert(msg.d [0]);

但是对于我的失望,我只得到“[”这就是结果。那么,请你帮忙我如何只访问EVENT_TYPE_ID值?

   $.ajax({
            type: "POST", url: "Data.aspx/CheckInsertRecord",
            data: "{EventType:'" + eventtype + "',BeginDate:'" + begindate + "'," +
                   "EndDate:'" + enddate+"' }",
            contentType: "application/json; charset=utf-8", dataType: "json",
            success: function (msg) {

       //var prof = eval("(" + msg.d+ ")")
           var data = $.parseJSON(msg.d);

        alert(msg.d[0]);
           alert("A record of this event already exists in the database.\n" + msg.d+".");


            }
        });

这是JSON字符串

{
  "EVENT_TYPE_ID": 1,
  "BeginDate": "2011-06-03",
  "EndDate": "2011-06-11",
  "BeginLAT": null,
  "BeginLONG": null,
  "EndLAT": null,
  "EndLONG": null
}

3 个答案:

答案 0 :(得分:0)

我认为这应该有效,

$.getJSON('Data.aspx/CheckInsertRecord', {EventType:eventtype,BeginDate:begindate,EndDate:enddate}, function(data){
 alert(data["EVENT_TYPE_ID"]);
});

alert(msg.d["EVENT_TYPE_ID"]);

答案 1 :(得分:0)

无效的原因是您将$.parseJSON()的结果分配给data,但之后尝试通过msg.d访问该对象,这仍然只是JSON字符串。字符串也可以作为JavaScript中的字符数组进行访问,因此msg.d[0]实际上是引用JSON的第一个字符,即开放数组括号。

如果您使用了data[0],那么您将获得所需的内容。但是,我强烈建议不要继续沿着这条路走下去。

在这种情况下,您可能没有意识到ASP.NET automatically handles JSON serialization for you。您在那里手动构建的JSON字符串将再次自动进行JSON序列化。在客户端,jQuery接收带有返回值的ASP.NET生成的JSON字符串,解析它,然后将内部JSON字符串交给你,然后再进行第二次解析。客户端和服务器上的重复工作都是不必要的低效率。

在服务器端执行此操作:

public static IEnumerable CheckInsertRecord(String EventType, String BeginDate, String EndDate)
{


  var query = // Your LINQ query here

  // You can simplify this by just returning the result. If it's empty,
  //  it's easy to test for that on the client-side - easier than watching
  //  for the magic string.
  return query;
}

然后,在jQuery完成自动反序列化后,您将立即在客户端访问它:

$.ajax({
  type: "POST", 
  contentType: "application/json",
  url: "Data.aspx/CheckInsertRecord",
  data: "{EventType:'" + eventtype + "',BeginDate:'" + begindate + "'," +
        "EndDate:'" + enddate+"' }",
  success: function (msg) {
    if (msg.d.length === 0)
      alert("No duplicate");
    else
      alert(msg.d.length + " duplicate events already exist!");
  }
});

很好,也很容易。

如果您对我更改$ .ajax()参数的原因感到好奇,请参阅此帖子了解一些information on how you can eliminate some extraneous verbosity from jQuery calls to ASP.NET services

答案 2 :(得分:-1)

检索并浏览JSON对象:

$.getJSON(
  url,
  { p1:p1,
    p2:p2 
  },
  function(data){
     $.each(data, function(key, val) {
         alert("key:"+key+";val:"+val+"-"); 
     });
  }
};