ajax - 仅当通过 AJAX 响应更改某些内容时才更改选项
问题描述
关于 Symfony 的 AJAX 响应,我需要您的帮助。在我的页面上,我有选择选项并且只想刷新它们,如果数据库中的任何内容发生了变化。现在我每五秒加载一次并检查数据计数是否不同。但另一方面,用户也可以编辑/重命名旧选项。如果我只检查计数,则无法刷新列表。那么如何检查旧响应是否与新响应不同?
提前致谢!!(我在JS中的代码如下)
let Routing = require('../../vendor/friendsofsymfony/jsrouting-bundle/Resources/public/js/router')
let Routes = require('./js_routes')
Routing.setRoutingData(Routes)
let select_options = document.getElementById("person_names")
document.addEventListener('DOMContentLoaded', function (event) {
if(window.location.href.indexOf("entity=Person&action=new") > -1 || window.location.href.indexOf("entity=Person&action=edit") > -1){
let firstRequest = true;
let responseOld
window.setInterval(function () {
new Promise( function (resolve, reject) {
let url = Routing.generate('getNewPersonList')
let xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
xhr.addEventListener('load', function (event) {
if (this.status === 200 && this.statusText === "OK"){
resolve(JSON.parse(this.responseText))
} else {
reject(JSON.parse(this.responseText))
}
})
xhr.send()
})
.then((response) => {
debugger;
if (firstRequest){
responseOld = response
firstRequest = false
// document.cookie = "Names=" + response + "; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/refreshNames";
console.log("first")
}
if (select_options.length !== response.length) {
console.log(select_options)
console.log(response)
// Drop old options
select_options.length = 0
// Fill it with new names
for (let index = 0; index < response.length; index++) {
let $option_element = document.createElement('option')
$option_element.value = response[index].id
$option_element.text = response[index].name
select_options.appendChild($option_element)
}
}
})
.catch((error) => {
console.log(error)
})
}, 5000)
}
})
解决方案
推荐阅读
- javascript - 使用 IntersectionObserver 检查跨域 iframe 是否即将与父页面相交
- jquery - 更改特定 div 类的 iframe src
- ajax - ajax 无法发布 /index.html 科尔多瓦
- c# - JCF Sketch-One Text is Placed,无法选择编辑或删除
- amazon-web-services - 从 S3 存储桶读取的 AWS Glue 限制数据
- javascript - Vuejs变量在函数谷歌地图矩阵api问题中使用
- reactjs - React Native - 在功能组件中使用 ref
- python-3.x - 使用 python3 播放 MP3 块
- reactjs - React Native Hooks 无法导入 无法解决依赖树
- c# - 尝试反序列化 JSON 对象数组,其中对象具有数组作为属性。我可以将数组元素映射到类的特定属性吗?