从文件中读取数据并在浏览器上显示

问题描述:

我是javascript新手(主要工作在后端),但现在我想创建一个可视化文件,并希望为其使用JavaScript。从文件中读取数据并在浏览器上显示

我已经保存在一个文件中的数据格式

id1 uid1 rating 
id1 uid2 rating2 

刚上手,我想从这个文件中读取数据,并在我的浏览器显示呢? 我是否需要启动服务器..或者我可以这样做。

任何建议/方向将不胜感激。 THanks

您需要了解ajax,并处理浏览器差异。这将在Firefox和Chrome工作方式是:

<body> 
    <div id="log"></div> 
    <script type="text/javascript"> 
    var request = new XMLHttpRequest();//depends on the browser , several ways to create the object 
    request.onreadystatechange = function(e){ 
     if(request.readyState == 4 && request.status==200){ 
     // do whatever you need with the data 
     document.getElementById("log").innerText = request.responseText; 
     } 
    } 
    // assuming the file is called data and is located on current-path-on-server/data 
    request.open("GET","data",true); 
    request.send(); 
    </script> 
    </body> 

更多一点:

https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started