javascript - 通过从 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"
解决方案
您只需要一个循环即可通过 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 来提供它。请参阅其文档。
推荐阅读
- php - 如何设置下拉codeigniter中选择的值
- mysql - 通过多个类别对表进行排名
- typescript - 如何从外部函数渲染组件
- javascript - 从包含 c# 变量的文件中执行 JS 脚本
- android - 从系统级别禁用所有无线电;AOSP
- c - 使用 EC_KEY 时 EVP_PKEY_verify 不起作用
- reactjs - 自动填充的输入字段会触发哪个事件?
- javascript - 为什么需要使用 promise 作为异步回调的包装器
- docker - 在 Windows10 hyper-V 上运行的 Docker Desktop for Windows 无法在 Oracle Virtualbox 6 中运行
- php - 如何在图像中添加产品永久链接标签 woocommerce 购物车项目?