2016-06-13 62 views
-2
<!DOCTYPE html> 


<html> 
    <head> 
     <title></title> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> 
    </head> 
    <body> 
    <select id="people"></select> 
    </body> 

    <script type="text/JavaScript"> 
     $select = $('#people'); 
     //request the JSON data and parse into the select element 
     $.ajax({ 
      type:'POST', 
      url: './Person.JSON', 
      dataType:'JSON', 
      success:function(data){ 
       //clear the current content of the select 
       $select.html(''); 
       //iterate over the data and append a select option 
       $.each(data.person, function(key, val){ 
        $select.append('<option id="' + val.id + '">' + val.name + '</option>'); 
       }) 
      }, 
      error:function(){ 
       //if there is an error append a 'none available' option 
       $select.html('<option id="-1">none available</option>'); 
      } 
     }); 
    </script> 
</html> 

喜從本地JSON文件中的數據無法使用jQuery來readed ajax.even 我試圖使用$ .getjson()一樣來加載從本地JSON文件中的數據,輸出不能加載。如何使用jQuery AJAX

請幫幫我。

這是我的Plunker

https://plnkr.co/edit/?p=preview

+1

它是一個空的重擊器 – brk

+1

你提到「本地json文件」。你是否試圖從用戶本地磁盤上的文件讀取?這是不可能的。 – ADyson

+0

我想你應該看看這個@GOPAL http://api.jquery.com/jquery.getjson/ –

回答

0

這裏有如下一個鏈接來引導你:

http://www.html5rocks.com/en/tutorials/file/dndfiles/

還有另一種方式也做同樣的: 它使用使用FileReader和JSON.parser(並沒有jQuery)。

<script type="text/javascript"> 

    function loadFile() { 
    var input, file, fr; 

    if (typeof window.FileReader !== 'function') { 
     alert("The file API isn't supported on this browser yet."); 
     return; 
    } 

    input = document.getElementById('fileinput'); 
    if (!input) { 
     alert("Um, couldn't find the fileinput element."); 
    } 
    else if (!input.files) { 
     alert("This browser doesn't seem to support the `files` property of file inputs."); 
    } 
    else if (!input.files[0]) { 
     alert("Please select a file before clicking 'Load'"); 
    } 
    else { 
     file = input.files[0]; 
     fr = new FileReader(); 
     fr.onload = receivedText; 
     fr.readAsText(file); 
    } 

    function receivedText(e) { 
     lines = e.target.result; 
     var newArr = JSON.parse(lines); 
    } 
    } 
</script> 

</body> 
</html> 

以往更多的getJSON也應該工作,您使用的getJSON後解析JSON對象?

+0

一個簡單的解決方案太複雜的東西 –