2014-02-20 26 views
0

雖然這是工作的代碼我只是需要與親的檢查,以確保這是處理結果正確的方法,使他們可以用在獲取JavaScript結果HTML使用HTML ...正確的方式使用JSON編碼數組與AJAX

(被請求的信息是從MySQL數據庫查詢的JSON編碼的PHP數組)

的JavaScript:

function getPlaylist() { 
    var xmlhttp, 
    timer; 

    if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } 
    else { 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      var list = eval ('('+xmlhttp.responseText+')'); 
      { 

       document.getElementById("list0artist").innerHTML=list[0].artist; 
       document.getElementById("list0title").innerHTML=list[0].title; 
       document.getElementById("list0label").innerHTML=list[0].label; 
       document.getElementById("list0albumyear").innerHTML=list[0].albumyear; 
       document.getElementById("list0picture").innerHTML='<img src="/testsite/covers/' + list[0].picture + '" width="169" height="169"/>'; 
      } 
     } 
    }; 

    xmlhttp.onerror = function() { 
     clearTimeout(timer); 
    }; 

    xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true); 
    xmlhttp.send(); 

    timer = setTimeout(getPlaylist, 1000); 
} 

然後在HTML中,它是對我們正確e用body onload="getPlaylist()命令加載JavaScript函數?使用div id="list0artist輸出我的JavaScript變量是否正確?

HTML:

<!doctype html> 
<html> 
    <head> 
     <script src="/testsite/OneSecondPlaylist.js"></script> 
     <meta charset="utf-8"> 
     <title>test</title> 
    </head> 

    <body onload="getPlaylist()"> 
     <div id="wrapper"> 
      <div id="list0artist"></div> 
     </div> 

     <div id="wrapper"> 
      <div id="list0title"></div> 
     </div> 
    </body> 
</html> 

回答

1

不要使用eval (eval is evil)

爲了讓您的XMLHttpRequest的結果,你可以使用JSON.parse()方法

所以,在你的代碼,更換該list assignement通過:

更新:最好成績的做法更清晰的JS開發

xmlhttp.onreadystatechange = function() { 

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 

     // Simple checkup to verify the well functionment of JSON.parse 
     // If the xmlhttp.responseText isn't JSON valid, the browser goto the `catch` part (see below) 
     try { 
      var list = JSON.parse(xmlhttp.responseText); 

      if (list && typeof list === 'object') { 

       // your list seems to be an array of object ? 
       // so, we loop on this list 
       // if list contains 0 element, this part is skipped 
       for (var i = 0; i < list.length; i++) { 

        var currentItem = list[i]; 

        document.getElementById("list0artist").innerHTML = currentItem[0].artist; 
        // to continue ;-) 
       } 

      } 

     } catch(e) { 

      throw new Error("Bad response..."); 

     } 

    } 
}; 
+0

謝謝..我只是讀throught您鏈接的文檔......你想想代碼documentgetelement線什麼..這是迴歸的最佳途徑文字 – Justin

+0

平原串看到我更新的代碼示例,說明;-) –

+0

代碼不再輸出數據,我加了一個「}」的代碼結束,因爲我覺得一個是失蹤,但仍然沒有喜悅...(只是櫃面這有助於這裏是我的編碼數據的樣子)http://jsfiddle.net/Musicman/PWQN2/ – Justin