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>');
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度