首页 > 解决方案 > 仅当通过 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)
    }
})

标签: ajaxsymfonyresponse

解决方案


推荐阅读