2016-07-27 214 views
2

基本設置是一個簡單的JSON文件,我通過ajax將其拉入頁面。現在我知道了工作的罰款,此代碼從JSON中提取多個數據集

$(document).ready(function() { 
      var tour = $('.js-featureTour'); 
      $.ajax({ 
        type: "GET", 
        url: "tour.json", 
        dataTyple: "json", 
        success: function (result) { 
         var imgSrc = result.image; 
         $('.js-featureTourTitle').text(result.tourTitle); 
         $('.js-featureTourDesc').html(result.tourDesc); 
         $('.js-featureTourImg').attr('src', imgSrc); 
        } 
       }) 
      }); 

這與我的測試JSON文件效果很好,但我確實有一起工作是這樣的

{ 
    "tour1": { 
     "tourTitle": "Test Title 1", 
     "tourDesc": "description 1", 
     "image": "/main1.jpg" 
    }, 
    "tour2": { 
     "tourTitle": "Test Title 2", 
     "tourDesc": "description 2", 
     "image": "/main2.jpg" 
    }, 
    "tour3": { 
     "tourTitle": "Test Title 3", 
     "tourDesc": "description 3", 
     "image": "/main3.jpg" 
    } 
} 

我真正想要的是爲了成功讀取「tour1」中的內容,將其插入頁面,然後等待一段時間,然後閱讀「tour2」中的內容,然後寫入「tour1」信息,然後執行「tour3」的相同操作。有人可以幫我從這裏出去嗎?我一直堅持這一點的時間超過了我的承認。任何幫助是極大的讚賞。

回答

1

您需要遍歷Json對象並使用SetTimeout來延遲DOM中數據的操作。嘗試下面的代碼。

success: function (result) { 
    $.each(results, function(i,result) { 
     setInterval(function(){ 
      var imgSrc = result.image; 
      $('.js-featureTourTitle').text(result.tourTitle); 
      $('.js-featureTourDesc').html(result.tourDesc); 
      $('.js-featureTourImg').attr('src', imgSrc); 
     },5000) 
    }) 
} 
+0

嘿!感謝您的迴應。這種有點奏效,但它不顯示tour1和tour2,而是等待5秒,然後顯示tour3 – Damien

+0

嘗試使用上面的代碼。我已經修改它通過使用$ .each而不是foreach –

+0

再次感謝,我仍然得到相同的結果,但:(這是我第一次跳入ajax/JSON,所以道歉爲做noob – Damien

0

你可以用setInterval做到這一點:

function handleTours(json) { //call this from the callback 
    var elements = []; //build a set of elements which will help 
    for (key in json) { 
     elements.push(key: key, structure: json[key]); 
    } 
    if (elements.length > 0) { //if there are no elements, do nothing 
     var index = 0; 
     var intervalID = setInterval(function() { //we store intervalID to stop the repetition when we are at the end of the set 
      if (index >= elements.length) { 
       clearInterval(intervalID); //we are at the end of the set 
      } else { 
       //do something with elements[index].key and elements[index].structure 
       index++; 
      } 
     }, 5000); 
    } 
} 
0
只是爲了記錄

我得到了它這個

success: function (result) { 
        var time = 0; 
        $.each(result, function(i, result) { 
         setTimeout(function(){ 
          var imgSrc = result.image; 
          $('.js-featureTourTitle').text(result.tourTitle); 
          $('.js-featureTourDesc').html(result.tourDesc); 
          $('.js-featureTourImg').attr('src', imgSrc); 
          },time) 
          time += 5000; 
         }) 
        } 

感謝您的幫助工作!