2013-11-22 2 views
0

Я работаю над этим как час, но, похоже, не могу понять.JQuery доступ к некоторым данным JSON

Ответ JSON:

{"lastDate":"2013-11-22 00:00:35", 
"lastId":"42460", 
"response":[ 
{ 
"class":"rowgreen", 
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;", 
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;", 
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;", 
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;", 
"server":"Test\\u0026nbsp;" 
} 
]} 

Это кажется правильным, теперь JQuery:

function longPolling() { 
    if (!longPollingAllowed) { 
     return; 
    } 
    console.log("Long polling started."); 
    $.ajax({ 
     url: "logpersonal_ajax.php", 
     data: { 
      serverId: serverId, 
      playerName: playerName, 
      lastDate: lastDate, 
      lastId: lastId 
     }, 
     cache: false, 
     dataType: "json", 
     beforeSend: function() { 
      longPollingBusy = true; 
     }, 
     success: function(json) { 
      console.log("success"); 
      $(json).each(function() { 
       console.log("this.lastDate = " + this.lastDate); 
       console.log("this.lastId = " + this.lastId) 
       console.log("this.response = " + this.response); 
       console.log(this.response); 
       this.lastDate = this.lastDate; 
       this.lastId = this.lastId; 
       if (this.response != "") { 
        this.response.each(new function() { 
         console.log(this); 
         var clazz = this.class; 
         console.log("clazz = " + clazz); 
         var id = this.id; 
         var date = this.date; 
         var player = this.player; 
         var target = this.target; 
         var weapon = this.weapon; 
         var server = this.server; 
         var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n"; 
         console.log("string = " + string); 
         $(string).insertBefore($("#list tr.header").next());    
        }); 
       } 
      }); 
      if (lastDate != "" && lastId != "") { 
       //longPolling(serverId, playerName, lastDate); 
      } 
      longPollingBusy = false; 
     }, 
     error: function(json, message) { 
      console.log("fail: " + message); 
      longPollingBusy = false; 
     } 
    });  
} 

В console.log("this.lastDate = " + this.lastDate); работает, так что делает один для this.lastId. this.response также работает и прекрасно показывает массив, начинающийся с индекса 0, и при его расширении вы можете видеть все элементы в представлении разработчика.

Теперь приходит часть я не могу понять: На foreach над this.response он ничего полезного (кроме прототипа скелета) для this не печатает.

Как получить доступ к значениям?

+1

Когда вы говорите * «foreach» *, ссылаетесь ли вы на эту строку? 'this.response.each (new function() {' вероятно, это должно быть 'forEach'. После того, как это было изменено на' forEach', вам нужно будет использовать параметры обратного вызова, а не 'this', чтобы получить доступ к значениям массива –

+0

'this.response.each' не должен работать, поскольку массивы не имеют метода' each'. Кроме того, 'new function() {...}', безусловно, неверно. т.е. объект) функции '.each'. Я также предлагаю вам быть последовательным: либо использовать методы jQuery, либо использовать собственные методы JS. –

+0

Почему вы используете итератор здесь' $ (json) .each (function() {'? Корневой элемент не является массивом. Вы действительно пытаетесь перебрать свойства возвращаемого объекта? Это не похоже на то, что вы пытаетесь использовать такие вещи, как' this.lastId' –

ответ

3
this.response.each(new function() { 

Эта строка неверна. Это должно быть:

this.response.forEach(function() { 

P.S. Я предлагаю сделать $.each(json, function(){ вместо $(json).each(function() {.

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