首页 > 解决方案 > 通过从 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"

标签: javascriptjqueryhtmlajax

解决方案


您只需要一个循环即可通过 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);

  });
}

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

如果您使用 FullCalendar(我认为它是最流行的日历插件),那么有一种最有效的方法可以使用 json 来提供它。请参阅其文档


推荐阅读