我想从我的第二个网站(子域名)获取HTML并使用它来构建此网站的一部分。
HTML网站:
<head>
<body>
<div id = "items">
<div id = "#one">
<ul>
<li><a href = "#">Click here</a></li>
<li><img src = "/images.png" /></li>
</ul>
</div>
<div id = "#two">
<ul>
<li><a href = "#">Click here</a></li>
<li><img src = "/images2.png" /></li>
</ul>
</div>
</div>
</body>
</head>
我想做一些事情,比如计算div元素的数量,获取列表等等。
这就是我的尝试:
$.ajax({
url: '/mysite/items.html',
success: function(data) {
//Need to manipulate here
var html = $(data);
var items = $.get(".items", html);
var numItems = $('.items').length;
console.log(data); //There is data(Whole HTML is here.)
console.log(items); //This is undefined??
console.log(numItems): //This is undefined??
var raw = html.get(".offers"); //Complains doesnot have a get method??
},
});
答案 0 :(得分:2)
从我能看到你想要的东西
$.ajax({
url: '/mysite/items.html',
success: function (data) {
//Need to manipulate here
var $html = $(data);
//use .find() to find elements with class items in data
var $items = $html.find('.items');
//use the items object to get the length
var numItems = $items.length;
console.log(data);
console.log($items);
console.log(numItems):
//need to use .find() to get the elements matching a selector
var raw = $htm.find(".offers");
},
});
答案 1 :(得分:0)
由于源同源安全策略,Javascript无法从其他域加载非JavaScript文件。如果您拥有这两个网站,则可以启用CORS
否则您将需要服务器端语言作为代理