wen tian wen tian - 1 year ago 53
jQuery Question

Ajax Return data Do not repeat content in jquery

When you click the button when the display of a content, and then click the button when the content hidden, and then click the button when the show repeat, I do not know how to solve the problem? Big god can help solve? Thank you very much!

HTML file

<button id="liuyan" type="button" class="btn btn-primary btn-lg">my click</button><div id="mydiv2">




JavaScript file

$("button#liuyan").on("click", function(e) {

e.preventDefault();

$.ajax({
url: 'http://localhost:3000/api/comment',
method: 'GET',
dataType: "jsonp",
async: false,
}).done(function(data, textStatus, jqXHR) {

var mydiv2 = $("#mydiv2");

if (mydiv2.css("display") === "none") {
mydiv2.show();
var mycode = document.createElement('div');
mycode.innerHTML = '<pre><code data-language="json">' + JSON.stringify(data, undefined, 2) + '</code></pre>';
Rainbow.color(mycode, function() {
document.getElementById('mydiv2').appendChild(mycode)
});
} else {
mydiv2.hide();

}

console.log(data);
console.log(jqXHR.responseText);
});

});

Answer Source

I dont have AJAX URL. I gave dummy data. It should work.

Every time, while showing you are appending the content with existing content. So it will repeat. So you have to remove the existing content in div and append it to div.

Add this line before appending

document.getElementById('mydiv2').innerHTML = '';

Then existing content will get cleared.

$("button#liuyan").on("click", function(e) {

        e.preventDefault();

           data = {
           "name":"hello"
           }

            var mydiv2 = $("#mydiv2");

            if (mydiv2.css("display") === "none") {
                mydiv2.show();
                var mycode = document.createElement('div');
                mycode.innerHTML = '<pre><code data-language="json">' + JSON.stringify(data, undefined, 2) + '</code></pre>';
                //Rainbow.color(mycode, function() {
                 document.getElementById('mydiv2').innerHTML = '';    
                 document.getElementById('mydiv2').appendChild(mycode)
                //});
            } else {
                mydiv2.hide();

            }

         //   console.log(data);
        //    console.log(jqXHR.responseText);
       // });

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="liuyan">Click</button>
<div id="mydiv2"></div>

Another Way:

You can make a call on ready function and show and hide when click on the button

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download