2013-02-12 5 views
0

У меня есть веб-служба C#, которая возвращает данные json. Вот данные, которые возвращаются.Неопределенное значение при получении значения из переменной json

[ { "destination": "pandora.com", "hits": 9 }, 
{ "destination": "google.com", "hits": 2 }, 
{ "destination": "msftncsi.com", "hits": 2 }, 
{ "destination": "nmlsconsumeraccess.org", "hits": 1 }, 
{ "destination": "facebook.com", "hits": 1 }, 
{ "destination": "gravatar.com", "hits": 1 }, 
{ "destination": "iheart.com", "hits": 1 }, 
{ "destination": "kiss1041fm.com", "hits": 1 }, 
{ "destination": "live.com", "hits": 1 }, 
{ "destination": "microsoft.com", "hits": 1 }, 
{ "destination": "today.com", "hits": 1 }, 
{ "destination": "update.microsoft.com", "hits": 1 }, 
{ "destination": "xsitesnetwork.com", "hits": 1 }, 
{ "destination": "youtube-nocookie.com", "hits": 1 }, 
{ "destination": "youtube.com", "hits": 1 }, 
{ "destination": "zillow.com", "hits": 1 } ] 

Вот мой JavaScript:

ret = Convert2Json.Convert(OnComplete, OnTimeOut, OnError); //this is my webservice 

function OnComplete(arg) { 

    $('#label').text(arg); //when I set this label to arg 
    //I get the json data correctly as above 

    var list = { 
     "entries": arg 
    }; 

    alert(list.entries[0].destination); 
    //this gives me undefined when it popups 
} 

function OnTimeOut(arg) { 
    alert("TimeOut encountered when calling server"); 
} 

function OnError(arg) { 
    alert("Error encountered when calling server"); 
} 

Если я определяю список себя следующим образом, она работает:

var list = { "entries": [{ "destination": "pandora.com", "hits": 9 }, { "destination": "google.com", "hits": 2 }, { "destination": "youtube.com", "hits": 2 }, { "destination": "facebook.com", "hits": 1 }, { "destination": "fdic.gov", "hits": 1 }, { "destination": "GOV_new", "hits": 1 }, { "destination": "iheart.com", "hits": 1 }, { "destination": "jcpportraits.com", "hits": 1 }, { "destination": "kiss1041fm.com", "hits": 1 }, { "destination": "live.com", "hits": 1 }, { "destination": "msftncsi.com", "hits": 1 }, { "destination": "publix.com", "hits": 1 }, { "destination": "today.com", "hits": 1 }, { "destination": "xsitesnetwork.com", "hits": 1 }, { "destination": "youtube-nocookie.com", "hits": 1 }] }; 

Вот что делает Convert2Json.Convert

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string Convert() { 




    using (SqlConnection conn = new SqlConnection("Server=localhost;Initial Catalog=Testing_Server;Trusted_Connection=True;")) 
    { 

     SqlCommand cmd = new SqlCommand("SELECT Destination as destination, count(distinct(source)) as hits FROM [Carlos_Test] where GETDATE() < DATEADD(MINUTE,5,time) and destination not in ('google-analytics.com','gstatic.com','googleadservices.com','download.windowsupdate.com') group by Destination order by hits DESC", conn); 




     conn.Open(); 


     List<VisitedSites> slist = new List<VisitedSites>(); 

     SqlDataReader reader = cmd.ExecuteReader(); 

     while (reader.Read()) { 



      VisitedSites vs = new VisitedSites(); 
      vs.destination = reader["destination"].ToString(); 
      vs.hits = Int32.Parse(reader["hits"].ToString()); 

      slist.Add(vs); 

     } 





     string jSon = JsonConvert.SerializeObject(slist, Formatting.Indented); 


     return jSon; 
    } 



} 

public class VisitedSites { 

    public string destination; 
    public int hits; 


} 
+1

'console.log (list, arg);' --- для целей отладки используйте 'console.log', а не' alert' – zerkms

+0

возможный дубликат [У меня есть вложенная структура данных/JSON, как я могу получить доступ к конкретное значение?] (http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value) –

+1

Возможно, вам придется сначала проанализируйте JSON ('arg'). Если '$ ('# label'). Text (arg);' показывает вам данные по мере их размещения, тогда 'arg' - это строка, а не массив. –

ответ

4

Согласно тому, что вы показали - arg - массив.

Так, скажет alert(list.entries[0].destination); может работать, что дает вам первый элемент, но alert(list.entries.destination); не буду, потому что list.entries массив, который не имеет .destination свойства, указанные.

+0

отредактированный код. list.entries [0] .Определение - это то, что я использую. Это то, что дает мне неопределенность. – user541597

+0

@ user541597: без результатов 'console.log' (см. Мой первый комментарий к вопросу) невозможно сказать что-то еще наверняка – zerkms

+1

@ user541597: Разбирали ли вы JSON, как я предложил? –

Смежные вопросы