Reputation:
Is jQuery.append necessary for what I want to do if not then how can I do this with out using append? And I don't want to use append because it makes copies of json outputs I just want to use a toggle button to hide and show the JSON results with a button. And I don't want to have the JSON results to output copies more than once. I assume that stackoverflow.com don't have a ajax
editor to show you this so I know the perfect editor you guys can use to show me how to do this. My code example is based on exactly on this example but mines have toggle attach to it but It failed. So here's the
AJAX editor LINK
And here's my failed attempt code example.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ").toggle();
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
and this is the JSON object code that is used in mine and w3schools example.
{
"firstName": "John",
"lastName": "Doe",
"age": 25
}
Upvotes: 0
Views: 81
Reputation:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var data = {
"firstName": "John",
"lastName": "Doe",
"age": 25
};
$(document).ready(function(){
$("button").click(function(){
//$.getJSON("demo_ajax_json.js", function(result){
$.each(data, function(i, field){
$("div").append(field + " ").toggle();
});
//});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
Because JSON File you are loading is not available.
Upvotes: 0
Reputation: 2982
Try this, what I have done is added empty()
so that the div
you are trying to append the data is set to empty i.e, $('div').empty();
just before append is used.
$(document).ready(function(){
$("div").hide();
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$('div').empty();
$.each(result, function(i, field){
$("div").append(field + " ").toggle();
});
});
});
});
Upvotes: 0
Reputation: 243
I think it should be something like this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
$("button").click(function(){
$('div').toggle();
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div style="display:none"></div>
</body>
</html>
Upvotes: 1