2012-06-15 57 views
1

我試圖從jQuery文件中恢復數據,但它不檢索任何數據,使用jquery!從json文件檢索數據

JSON文件數據:

[ 
{"optiontext" : "One", "optionvalue" : "One"}, 
{"optiontext" : "Two", "optionvalue" : "Two"}, 
{"optiontext" : "Three", "optionvalue" : "Three"} 
] 

和代碼,我試圖用訪問這個數據是:

<!doctype html> 
<html> 
    <head> 
     <script type="text/javascript" src="jquery.min.js"></script> 
    <script type="text/javascript"> 

    $(document).ready(function() { 
      $('#submit').click(function() { 
     $.ajax({ 

    //alert("I'm doing it now"); 
    //define the attributes for the connection 
    type:"GET", 
    url:"sample1.json", 
    dataType:"json", 
    //extrat the data 

    success: function (data) {  
    var SampleFileMessage="<ul>"; 
    $.each(data, function(i,n){ 
    SampleFileMessage+="<li>"+n["optiontext"]+"</li>"; 
      }); 
    SampleFileMessage+="</ul>"; 
    $('#message').append(SampleFileMessage); 
    document.writeln(SampleFileMessage); 
} 
}); 
return false; 
}); 
}); 


    </script> 
    </head> 
    <body> 
     <input type="button" onclick="getjson()" value="pressme"   style="align:center" />  
     <div id="messege" > <input type="button" id="submit" value=" get the  data from json" ></div> 
    </body> 
    </html> 

我我應該做處理這個JSON格式! !

+0

請使用'.getJSON' - http://api.jquery.com/jQuery.getJSON/,請嘗試使用絕對路徑('/ sample1.json')和使用Fiddler檢查文件是否被正確檢索。 – LukLed

+0

看起來像它對我有用:http://jsfiddle.net/CuwGc/1/你可能沒有正確引用你的JSON文件的位置......? – mVChr

+0

@mVChr我改變了usr,但invaine,他們默認在同一目錄下,感謝您的幫助! –

回答

0

試試這個:

$.each(data, function(i, n) { 
    SampleFileMessage += "<li>" + n.optiontext + "</li>"; 
});