Dug*_*ugi 1 html javascript jquery 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);
Run Code Online (Sandbox Code Playgroud)
和:
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
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用很奇怪.至少对我来说很奇怪.这是我在PHP中填充变量的方式,所以我对JS进行了相同的逻辑.也许有另一种方式?
PS: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
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:添加了一个演示!
我重读了你的问题,我注意到你正在调用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!
}
});
Run Code Online (Sandbox Code Playgroud)
要么
$.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!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17480 次 |
| 最近记录: |