weixin_33725239 2017-11-20 23:12 采纳率: 0%
浏览 54

为什么ajax请求重复?

I am trying to get the todo titles from jsonplaceholder.typicode.com JSON. I have three buttons and each botton has and id, that id is related to the json todo. When you click on a botton you see the title of that json todo.

Button 1 = jsonplaceholder.typicode.com/todos/1
Button 2 = jsonplaceholder.typicode.com/todos/2
etc..

$('button').click(function (event) {
    var id = event.target.id;
    console.log(id);
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/todos/" + id,
        type: "GET"
    }).done(function (data) {
        $('#result').append('<div class="todo"></div>');
        $.each(data, function (key, value) {
            if (key == "title") {
                $('.todo').append('<p>' + key + ': ' + value + '</p>');
            }
        });
    }).fail(function (event) {
        alert(event.status);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1">A</button>
<button id="2">B</button>
<button id="3">C</button>
<div id="result">
</div>

The problem is that titles repeat each time I click on a button. Why this occurs?

</div>
  • 写回答

2条回答 默认 最新

  • 谁还没个明天 2017-11-20 23:17
    关注

    Why? Because you append another <div class="todo"></div> each time button is clicked and then append the content to every one that exists

    You can isolate the new <div class="todo"> and only append the new content to that

    var $todo = '<div class="todo"></div>'
    $('#result').append($todo);
    $.each(data, function(key, value) {
      if (key == "title") {
        $todo.append('<p>' + key + ': ' + value + '</p>');
      }
    });
    

    Or empty the $('#result') before you add the new content if you don't want to see the first set by changing:

    $('#result').append('<div class="todo"></div>');
    

    To

    $('#result').html('<div class="todo"></div>');
    
    评论

报告相同问题?