在jQuery/JS中将文件读取为字符串

Reading a file into a string in jQuery/JS

本文关键字:文件 读取 字符串 jQuery JS      更新时间:2024-04-07

标题不言自明:我需要通过jQuery读取一个HTML文件,并将其内容存储到一个字符串变量中。

我尝试使用.load$.get,但它们不能满足我的需要。

这是我迄今为止尝试过的代码,基于下面的注释,但它们根本没有填充我的template变量:

var template = "";
$.ajax({
    url: 'includes/twig/image_box.twig',
    type: 'get',
    success: function(html) {
        var twig = String(html);
        template.concat(twig);
    }
});
console.log(template);

AND:

var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
    var html = String(text);
    template.concat(html);
    // console.log(html); // WORKS!
});
console.log(template); // Does not work

奇怪的是为什么这不起作用。至少对我来说很奇怪。这就是我在PHP中填充变量的方式,所以我在JS中携带了相同的逻辑。也许还有别的办法?

p.S:V我也尝试过所有的替代方法,比如用+=连接,并在回调函数内部用=分配模板,但都没有成功。

感谢那些试图帮助我的人!

也许您应该尝试使用$.AJAX()的AJAX请求

在这里查看jQuery API

    $.ajax({
            url: 'yourHTMLfile.html',
            type: 'get',
            async: false,
            success: function(html) {
                    console.log(html); // here you'll store the html in a string if you want
            }
    });

演示

编辑:添加了一个演示!

我重读了你的问题,注意到你正在调用ajax请求上方的控制台日志,但你忘记了ajax是异步的,这意味着页面将执行请求,并且只有在响应返回成功时(如果返回)才会设置模板值。因此console.log(模板)不会出现,因为它可能还没有加载。

var template = "";
$.ajax({
    url: 'includes/twig/image_box.twig',
    type: 'get',
    success: function(html) {
        var twig = String(html);
        template.concat(twig);
        console.log(template); // the change!
    }
});

$.ajax({
    url: 'includes/twig/image_box.twig',
    type: 'get',
    async: false,
    success: function(html) {
        var twig = String(html);
        template.concat(twig);
    }
});
console.log(template); // the change!

你可以试试这个:

//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
   //text argument is what you want
});

如果不起作用,请尝试您的浏览器是否可以打开该文件。如果可以的话,你最好在jQuery中尝试ajax方法。如果不能,你可能会在应用服务器中遇到一些关于权限之类的问题。