I am looking to create multiple html files for each phone-brand with a common '.js' file and '.json' file. I am trying to replace the word ‘Brand’ in the common '.js' file with the respective brand name each time and get the respective data from the '.json' file.
I am using a separate '.js' and '.json' file residing in the same folder as my html file. Then using the ‘text.replace’ command in each html file, I’m trying to get the relevant data from my JSON file through the common '.js' file.
My html file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="GetLocalJSON.js" type="text/javascript"></script>
</head>
<style>
</style>
<body>
<div id="AboutTab">
<div id=About>
</div>
</div>
</body>
<script>
$(document).ready(function(){
var url = "GetLocalJSON.js";
$.getScript( url, function() {
$(document.body).find('Brand').each(function() {
var text = $(this).text();
$(this).text(text.replace('Brand', 'Samsung'));
});
});
});
</script>
</html>
My GetLocalJSON.js jQuery file:
$(document).ready(function(){
var StatJSON;
jQuery.getJSON("QueryJSONData2.json", function (json) {
StatJSON = json;
var markup = '';
markup += '<div>'+ StatJSON.Phone.Brand[0].Size +'<div>'
$("#About").html(markup)
});
});
My QueryJSONData2.json JSON file:
{
"Phone": {
"Samsung":[{
"Size" : "AAA",
"Camera" : "BBB",
"Weight" : "CCC"
}],
"Apple":[{
"Size" : "XXX",
"Camera" : "YYY",
"Weight" : "ZZZ"
}]
}
}
The error I am getting is "Uncaught TypeError: Cannot read property '0' of undefined" at the line :
markup += '<div>'+ StatJSON.Phone.Brand[0].Size +'<div>'
which means my "text.replace" jquery command is not being action-ed. How do I fix this???
Your
QueryJSONData2.jsonis having no property namedBrandinsidePhoneobject.So,
StatJSON.Phone.Brand[0].Sizewill break, since yourReplacejquery command will have no impact on yourStatJSONobject.I am not sure what exactly you are trying to achieve using replace, but I am guessing if you want to replace
SamsungwithBrand, then you should do it inside yourGetLocalJSON.jsfile.One possible transformation is shown below.
Make sure you have transformed your data correctly, before you use it in your HTML.
This should give you some direction to fix it.