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

时间:2013-12-05 12:28:45

标签: javascript jquery html file

标题是不言自明的:我需要通过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);

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我也尝试了所有其他方法,例如与+=连接,并将回调函数内部分配给=的模板,但没有任何效果。

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

2 个答案:

答案 0 :(得分:7)

也许您应该尝试使用$ .ajax()

的AJAX请求

检查jQuery API here

    $.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
            }
    });

DEMO

编辑:添加了演示!

我重读了你的问题,我注意到你正在调用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!

答案 1 :(得分:1)

你可以试试这个:

//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方法,如果不是你可能在应用程序服务器中有关于权限或某些事情的问题。