AJAX reading from file

落爺英雄遲暮 提交于 2020-01-21 09:59:46

问题


I'm reading from a text file using AJAX. How do I read only the first line?


回答1:


This code should help you read from a remote text file:

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
  if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
    if (txtFile.status === 200) {  // Makes sure it's found the file.
      allText = txtFile.responseText; 
      lines = txtFile.responseText.split("\n"); // Will separate each line into an array
    }
  }
}
txtFile.send(null);



回答2:


It depends on how you output the file on the back-end. Depending on a language, be it PHP, Java or other, you can read the first line of your file and output it to the response.

To find out whether a file has changed: HTTP code 304 and browser-side caching may help in this case.



来源:https://stackoverflow.com/questions/5437447/ajax-reading-from-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!