2013-03-21 4 views
0

jQuery/Javascript를 사용하여 JSON 파일의 내용을 HTML 페이지로로드하려고합니다.자바 스크립트로 JSON 파일 내용로드

페이지를로드하려고 할 때마다 빈 페이지가 있습니다.

index.html을

<!DOCTYPE html> 
<html> 
<head> 
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
    <meta content="utf-8" http-equiv="encoding"> 
    <style>img{ height: 100px; float: left; }</style> 
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> 
</head> 
<body> 
<div id="products"> 

</div> 
<script> 
    var my_json; 
    $(function(){ 
     $.getJSON('products.ajson', function(data) { 
      var output="<ul>"; 
      for (var i = 0; i < data.Products.length; ++i) { 
       output+="<li>" + data.Products[i].Name + " " + data.Products[i].Album + "--" + data.Products[i].Label+ data.Products[i].Tracks + data.Products[i].Price + data.Products[i].Genre+"</li>"; 
      } 

      output+="</ul>"; 
      document.getElementById("products").innerHTML=output; 

     }); 
    }); 
</script> 
</body> 
</html> 

products.json

{ 
    "Products": [ 
     { "Name": "Pink Floyd", 
      "Album": "The Best Of Pink Floyd: A Foot In The Door", 
      "Label": "EMI UK", 
      "Tracks":"Hey You, See Emily Play, The Happiest Days Of Our Lives, Another Brick in The Wall (Part 2), Have a cigar, Wish You Where Here, Time, The Great Gig in the Sky, Money, Comfortably Numb, High Hopes, Learning to Fly, The Fletcher Memorial Home, Shine On You Crazy Diamond, Brain Damage, Eclipse" , 
      "Price": "16.40", 
      "Genre": "Rock" 

     }, 
     { 
      "Name": "Depeche Mode", 
      "Album": "A Question Of Time", 
      "Label": "Mute", 
      "Tracks":"A Question Of Time, Black Celebration, Something To Do, Stripped, More Than A Party, A Question Of Time(extended), Black Celebration" , 
      "Price": "4.68" , 
      "Genre": "Rock" 
     }, 
     { 
      "Name": "Burial", 
      "Album": "Street Halo/Kindred", 
      "Label": "Hyperdub Japan", 
      "Tracks":"Street Halo, NYC, Stolen Dog, Kindred, Loner, Ashtray Wasp" , 
      "Price": "14.06", 
      "Genre": "Future Garage" 

     }, 

     { 
      "Name": "Aphex Twin", 
      "Album": "I Care Because You Do", 
      "Label": "1972 US", 
      "Tracks":"Acrid Avid Jam Shared, The Waxen Pith, Wax The Nip, Icct Hedral (edit), Ventolin (video version), Come On You Slags, Start As You Mean To Go On, Wet Tip Hen Ax, Mookid, Alberto Balsalm , Cow Cud Is A Twin, Next Heap With " , 
      "Price": "21.10", 
      "Genre": "Electronica" 
     }, 

     { 
      "Name": "Daft Punk", 
      "Album": "Discovery", 
      "Label": "", 
      "Tracks":"One More Time, Aerodynamic, Digital Love, Harder Better Faster Stronger, Crescendolls , Nightvision, Superheroes, High Life ,Something About Us, Voyager ,Veridis Quo, Short Circuit, Face To Face," , 
      "Price": "23.44" , 
      "Genre": "Nu-Disco" 
     }, 

     { 
      "Name": "Jean Michelle Jarre", 
      "Album": "Oxegene 2010", 
      "Label": "Oxegene", 
      "Tracks":"Oxegene 2010" , 
      "Price": "8.20", 
      "Genre": "Ambient" 
     }, 

     { 
      "Name": "Joy Division", 
      "Album": "In The Studio With Martin Hannett", 
      "Label": "Interstate", 
      "Tracks":"Digital Full Track, Noise Drums Sine Warm-up, Square Heat Ambience Workout, Glass - Breakout Full Track, Synth Ambience Warm-up, Ambience Atmosphere Warm-up, Atmosphere Setting Up, Drums & Bass Full Atmosphere Warm-up Silence, Atmosphere Full Track Metronome Intro - Hannett Intro Question Etc, Metronome Initial Adjustments #1, Metronome Initial Adjustments #2 Industrial Build Up Etc, Dead Souls Sound Check Drums Recognition Check, Dead Souls + Metronome Intro Adjustment Full Track Etc, Cups Smash 'Synth Filters Sweeps' Take #1, Hannett Interview Something Fishy, Ice Age Bass Ambience Warm-up, Full Track Ice Age, Bass Intro Noise Ambience, Clapping Drums Clapping Prog N4 Complete Full Track + Noise, Full Track N4 Programming + Noises, Full Eternal Track, More N4 Drum Programming Bass Guitar, N4 Industrial, N4 More Warm Up, Digital Ambience Warmth Rooms Warm-up - Shakin Speaker Dust Off" , 
      "Price": "22.27", 
      "Genre": "Rock" 
     }, 

     { 
      "Name": "Anthony Rother", 
      "Album": "Mother", 
      "Label": "Datapunk Germany", 
      "Tracks":"Mother, Cinema" , 
      "Price": "10.54", 
      "Genre": "Electro" 
     }, 

     { 
      "Name": "Gorillaz", 
      "Album": "Plastic Beach", 
      "Label": "EMI UK", 
      "Tracks":"Orchestral Intro, Welcome To The World Of The Plastic Beach, White Flag, Rhinestone Eyes, Stylo, Superfast Jellyfish, Empire Ants, Glitter Freeze, Some Kind Of Nature, On Melancholy Hill, Broken, Sweepstakes , Plastic Beach , To Binge , Cloud Of Unknowing , Pirate Jet " , 
      "Price": "7.02" , 
      "Genre": "Hip Hop" 
     }, 

     { 
      "Name": "Eminem", 
      "Album": "Recovery", 
      "Label": "", 
      "Tracks":"Cold Wind Blows, Talkin' 2 Myself (feat Kobe), On Fire , Won't Back Down (feat P!nk) ,WTP , Going Through Changes , Not Afraid , Seduction, No Love (feat Lil Wayne) , Space Bound , Cinderella Man , To Life, So Bad , Almost Famous , Love The Way You Lie (feat Rihanna) , You're Never Over, rack 17" , 
      "Price": "19.92", 
      "Genre": "Hip Hop" 

     } 
    ] 
} 

이런 일이 왜 어떤 생각 :

이 코드인가?

+0

왜 제품 div 안에 jquery를 배치합니까? – iAmClownShoe

+1

오류는 아니지만 다음과 같습니다. ''은 (는) 자신의 스크립트 태그 바로 위에 있어야합니다. 페이지의 "중간". – AD7six

+0

콘솔을 엽니 다. 콘솔 오류가 발생하지 않는지 확인하십시오. 오류 처리기를 ajax 호출에 추가하여 AJAX 호출이 성공했는지 또는 어딘가에서 오류가 발생하는지 확인할 수 있습니다. 응답에서 JSON을 되돌려 놓았는지 확인하십시오 –

답변

1

products.ProductsProducts.products이 역행했습니다. 반환 변수는 Products이라는 속성이있는 products입니다. 전화 번호는 products.Products입니다.

아마도 모호성을 피하기 위해 결과 변수 result 또는 그 외의 것을 입력하면 result.Products이라고 말할 수 있습니다.

또한 for..in 루프 대신 표준 for 루프를 권장합니다. Array 프로토 타입에 할당 된 다른 속성이있는 경우 (가능한 경우 - 일부 라이브러리는 indexOf과 같은 프로토 타입에 새로운 기능을 할당합니다) 문제가 발생합니다.

for (var i = 0; i < products.Products.length; ++i) { 
    // do something with products.Products[i] 
} 

자바 스크립트 오류가 발생했기 때문에 디버거를 통해이를 실행하면 볼 수 있습니다. 이런 이상한 것을 볼 때마다 콘솔 (Chrome dev tools, Firebug, IE dev tools 등)을 열면이 내용을 추적하는 데 도움이됩니다.

+0

이전 결과와 마찬가지로 previosuly, 빈 페이지. – Brian

+0

'products.Products'와'Products.products' 변수 (모두)를 재정렬하면 완벽하게 작동합니다. 그리고'products.json'이 HTML 페이지와 같은 디렉토리에 있고 IIS가 그것을 제공 할 수 있습니다. 디버거에서 콘솔을 보는 것 외에도 네트워크 탭에서 요청이 실제로 일어나는지 확인하십시오. –

+0

Firefox의 설정 일 수 있습니까? Products.Products 및 for 루프를 포함하여 모든 것을 변경하고 json 파일은 html 페이지와 같은 디렉토리에 있지만 작동하지 않습니다. – Brian

관련 문제