将html页面内容提取到var中

时间:2022-12-08 11:24:32

Just a small question here, that how do we get fetch the html content via ajax into a variable that I could use later.
Right now, I have a button on the click of which, I fetch another html page simply through load method as follows:
$('#container').load('http://127.0.0.1/someUrl')

这里有一个小问题,那就是如何通过ajax将html内容获取到一个变量中,以便我以后使用。现在,我点击了一个按钮,我通过load方法获取另一个html页面,如下所示:$('#container').load('http://127.0.0.1/someUrl')

I want to get the content into a var instead that I could at a later time use to append to the dom
$('#someContainer').append(someVar)

我想把内容放到一个var中,这样我以后就可以将其添加到dom $('#someContainer').append(someVar)

2 个解决方案

#1


2  

var someVar;

$.get("http://127.0.0.1/someUrl",function(data){
   someVar = data;
});

I would use $.get instead for this

我将使用美元。相反,这

#2


1  

Using jQuery/JavaScript, you can use AJAX if the file is on the same website:

使用jQuery/JavaScript,如果文件在同一个网站上,您可以使用AJAX:

var somevar;
$.get('myfile.html', null, function(data){
    // data will be the HTML
    somevar = data;
}, 'html');

If the file is from another website, you could try using JSONP, but I would recommend doing a local AJAX request to a PHP script and have PHP make a curl request to get the HTML instead. This will likely handle the request more efficiently and reliably than JSONP.

如果文件来自另一个网站,您可以尝试使用JSONP,但是我建议对PHP脚本执行一个本地AJAX请求,并让PHP发出一个curl请求来获取HTML。这可能比JSONP更有效、更可靠地处理请求。

#1


2  

var someVar;

$.get("http://127.0.0.1/someUrl",function(data){
   someVar = data;
});

I would use $.get instead for this

我将使用美元。相反,这

#2


1  

Using jQuery/JavaScript, you can use AJAX if the file is on the same website:

使用jQuery/JavaScript,如果文件在同一个网站上,您可以使用AJAX:

var somevar;
$.get('myfile.html', null, function(data){
    // data will be the HTML
    somevar = data;
}, 'html');

If the file is from another website, you could try using JSONP, but I would recommend doing a local AJAX request to a PHP script and have PHP make a curl request to get the HTML instead. This will likely handle the request more efficiently and reliably than JSONP.

如果文件来自另一个网站,您可以尝试使用JSONP,但是我建议对PHP脚本执行一个本地AJAX请求,并让PHP发出一个curl请求来获取HTML。这可能比JSONP更有效、更可靠地处理请求。