使用javascript读取文件

read file using javascript

本文关键字:文件 读取 javascript 使用      更新时间:2024-04-07

我试图使用JQuery读取和解析一个文本文件,但我使用的代码似乎出错了。

//Attempt 6
alert("Test Alert 9"); //js file does load into index.html
$.get( "exchanges.txt",
    function( data ) {
        //idk what the following two lines do, I got them from:
        //http://api.jquery.com/jquery.get/
  $( ".result" ).html( data );
  alert("check it");
    })
    //should execute if works?
    .done(function() {
        alert( "second success" );
    })
    //should execute if any error
    .fail(function() {
        alert( "error" );
    })
    .always(function() {
        alert( "finished" );
    });

打印以下警报:

  1. "测试警报9"
  2. "错误"
  3. "已完成"

我的问题:有没有办法检查错误是什么?和/或有人知道可能是什么错误吗?

编辑:为了澄清,exchanges.txt文件与js文件位于同一文件夹中

编辑:更新为向控制台抛出错误。错误打印:

 XMLHttpRequest cannot load      file:///C:/Users/Invictus/Documents/GitHub/BTCExchangesMaterialize/exchanges.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

通过将exchanges.txt移到主文件夹而不是js/文件夹来修复此错误。

新错误:

    XMLHttpRequest cannot load 
file:///C:/Users/Invictus/Documents/GitHub/BTCExchangesMaterialize/exchanges.txt.
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.jquery-2.1.1.min.js:4 n.ajaxTransport.k.cors.a.crossDomain.sendjquery-2.1.1.min.js:4 n.extend.ajaxjquery-2.1.1.min.js:4 n.each.n.(anonymous function)exchangesParser.js:3 (anonymous function)

$.get是$.ajax的一个shorcut,其中预先启用了一些设置。$.get的签名是:

$.get([String] url, [Object|String] urlparams, [Closure] callback);

AJAX查询成功后,callback被排除在外。

如果您计划使用jQuery promise方法,则可以省略成功回调,并使用其promise方法.done().fail().always()

成功回调方式

$.get( "exchanges.txt", function( data ) {
    $( ".result" ).html( data );
    alert("checked it");
});

承诺之路

$.get( "exchanges.txt")
.done(function( data ) {
    $( ".result" ).html( data );
    alert("checked it");
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

可以看出,promise在处理程序上更具体,因为您可以调用更多的函数,这是因为$.get(正如我之前提到的)是$.ajax的一个shorcut。看看扩展到$.ajax:的$.get调用

$.ajax方式

$.ajax({
    url: "exchances.txt",
    success: function(data){
        $(".result").html(data);
        alert("checked it");
    },
    error: function(response){
        alert("error");
    },
    complete: function(response){
        alert("done");
    },
});

请记住,当使用file://引用AJAX请求时,不能对本地文件执行AJAX请求。您应该通过http(apache、node)、ftp或任何其他您想要的协议来访问它们,但决不能在file:// 下访问

阅读更多:

jQuery承诺
jQuery ajax

fail函数中,传递response。然后你就可以玩响应对象了。检查浏览器的控制台(开发工具)

 .fail(function( response) {
        console.log("my error response is",response);
        alert( "error" );
    })