通过从AJAX respone获取价值来更改元素文本

时间:2018-12-05 13:53:39

标签: javascript jquery html ajax

我不确定我的方法是否正确,但是我的目标是发出请求,并且一旦收到响应,便会存储与某个类名匹配的所有元素,然后将每个元素的文本更改为响应的结果。

脚本:

$(document).ready(function() {
  $("#calendarBtn").click(function() {
    $("#calendar").show();
    $.ajax({
      url: "http://localhost:8000/calendar",
      success: function(result) {
        //Store elements
        var elems = document.getElementsByClassName("ei_Title");
        // Convert the NodeList to an Array
        var arr = jQuery.makeArray(elems);
        //iterate through each element
        $.each(arr, function(index, val) {
          //iterate through ajax response
          $.each(result, function(key, value) {
            console.log(key, value);
            var title = (result[key].title);
            //This is where I'm unsure as to how I set 
            the text of the element in "arr"
            to the "title"
            variable
          });
        });
      }
    });
  });
});

HTML:

 <div class="calendar_events">
        <p class="ce_title"></p>
        <div class="event_item">
          <div class="ei_Dot dot_active"></div>
          <div class="ei_Title"></div>
          <div class="ei_Copy"></div>
        </div>

响应:

{id: 6, title: "Walk the dog", date: "2018-12-05", assigned_to: "Sam", time: "11:00:00"}
assigned_to: "Sam"
date: "2018-12-05"
id: 6
time: "11:00:00"
title: "Walk the dog"

1 个答案:

答案 0 :(得分:1)

您只需要一个循环即可进行Ajax响应。然后,使用循环index,您可以检索json对象,并使用这些值设置“匹配”元素的文本。

success: function(result) {
  var elems = $(".ei_Title");

  //iterate through ajax response
  $.each(result, function(index, val) {

    // Set the title of each .ei_Title using the loop index.
    elems.eq(index).text(result[index].title);

  });
}

请注意,“ match”只是json对象和元素的顺序。

如果您使用FullCalendar(我认为这是最流行的日历插件),则有一种最有效的方式将它与json一起提供。参见其documentation

相关问题