简体   繁体   English

Javascript Fetch 只工作一次

[英]Javascript Fetch only works once

First of all thank you for any help you can give me.首先感谢您能给我的任何帮助。 I want to be able to dynamically activate/deactivate the status of a partner.我希望能够动态激活/停用合作伙伴的状态。 在此处输入图像描述

On each status change, a Bootstrap modal opens在每次状态更改时,都会打开一个 Bootstrap 模式在此处输入图像描述

For this I use Fetch() It works fine but only on the first action.为此,我使用 Fetch() 它工作正常但仅在第一个动作上。 If I then try on the same line again it doesn't work anymore.如果我再尝试在同一条线上,它就不再起作用了。 Same on another line.另一条线上也一样。 I have to reload the page so that I can redo the activation or deactivation action我必须重新加载页面才能重做激活或停用操作

Here is my code:这是我的代码:

 // Activation ou désactivation dynamique d'un partenaire //On boucle sur les input document.querySelectorAll(".form-switch-statut-partenaire input").forEach(input => { input.addEventListener("change", () => { //On récupère l'url de la route edit-statut const Url = input.dataset.path; const Modal = document.getElementById('exampleModal') const Footer = Modal.getElementsByClassName('modal-footer')[0].children[1] Footer.addEventListener("click", () => { //On lance la requête ajax fetch(Url, { headers: { } }).then((response) => { console.log(response); return response.json() }).then(data => { console.log(data) const content = document.querySelector('body'); content.innerHTML = data.content; }).catch((err) => console.log('Erreur: '+ err)); }) }); });

I can't find the solution despite my research尽管我进行了研究,但我找不到解决方案

Line 122 changes the whole body with the fetched data.第 122 行使用获取的数据更改整个主体。 This will remove all event listeners you previously set.这将删除您之前设置的所有事件侦听器。

Try to change only the HTML that actually changed in the response.尝试仅更改响应中实际更改的 HTML。 Fetching the whole body has probaly some network overhead that can be avoided.获取整个主体可能有一些可以避免的网络开销。

Or move the event listener registration to an init method and call that after swapping out the body.或者将事件侦听器注册移动到 init 方法并在换出主体后调用它。

thank you for your reply I had already tried to modify only the array data using (#formCheck)感谢您的回复我已经尝试使用(#formCheck)仅修改数组数据

 }).then(data => { console.log(data) const content = document.querySelector('#formCheck'); content.innerHTML = data.content;

The action works but my page is grayed out like my modal is open but it's not visible该操作有效,但我的页面显示为灰色,就像我的模态已打开但不可见

enter image description here在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM