在我们的网站上,<body>
标签包含各种data-*="*"
属性:
<body data-someData="someValue" data-someOtherData="someOtherValue">
我需要在其他页面上获取这些属性的值。因此,我使用 jQuery AJAX$.get
来获取页面的 HTML,从而获取这些数据属性。
我当前的脚本:
// The call (used on different pages)
var stock = getProductData('stock', '/some/product/url');
// The "GET" function
function getProductData(type, url) {
var jqxhr = $.get(url, function( data ) {
console.log('Data found!');
var $body = $(data).find('body');
var val = $body.data('stock');
console.log('Returning Value: "' + val + '"');
return val;
}).done(function(){
// Request is complete
console.log('getProductData Finished...');
}).fail(function(){
console.error( 'getProductData: ' + type + ' = FAIL / URL: ' + url);
});
}
所以有什么问题?好吧,$(data).find('body').data('stock');
它回来了undefined
。我也试过$(data).find('body').attr('data-stock');
了,但它返回了同样的东西。
那么,我怎样才能data-someData="someValue"
使用返回 body 标签的属性值$.get
呢?
上面示例中使用的data-stock
属性在我的产品页面上如下所示:
<body data-stock="3">
编辑:不重复:这个问题专门指解析元素的特定属性。我不是在问如何使用 AJAX 返回数据。