On our site, the <body>
tag holds various data-*="*"
attributes:
<body data-someData="someValue" data-someOtherData="someOtherValue">
I need to get the values of these attributes while on other pages. So, I am using jQuery AJAX $.get
to get the page's HTML, and thus these data attributes.
My current script:
// 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);
});
}
So, what's the problem? Well, the $(data).find('body').data('stock');
is coming back as undefined
. I also tried $(data).find('body').attr('data-stock');
, but it returned the same thing.
So, how can I return the body tag's data-someData="someValue"
attribute values using $.get
?
The data-stock
attribute used in the example above looks like this on my product page:
<body data-stock="3">
EDIT: Not a duplicate: this question refers specifically to the parsing of specific attributes of elements. I am not asking how to just return the data using AJAX.
` in HTML but in XML you need a closing tag. If you want something without a closing tag, you need to do `
`. HTML doesn't care. However, if you have `
` in your file, an XML parser will get confused. – dmeglio Apr 17 '15 at 20:11