簡體   English   中英

如何在不重新加載模態關閉頁面的情況下更新頁面內容?

[英]How can I update page content without reloading the page on Modal close?

我正在嘗試編輯頁面上的帖子,單擊編輯鏈接會打開一個模式,單擊保存按鈕,將編輯后的帖子保存在數據庫中,但我必須刷新頁面才能在屏幕上看到編輯后的帖子。 我希望在模式關閉后立即更新屏幕,但我不希望重新加載頁面。 如何在不重新加載頁面的情況下實現這一點?

視圖.py

def editTweet(request, post_id):
    postData = Posts.objects.filter(id = post_id)
    if request.method == "PUT":
        data = json.loads(request.body)
        print("data value is ", data)
    
        #updating data in the database where id = post_id
        Posts.objects.filter(id = post_id).update(postContent = data.get('postContent', None))

        print ("i'm inside PUT")
        return render(request, 'network/index.html')
    else:    
        print("i'm inside else")
        return JsonResponse([post.serialize() for post in postData], safe=False) 

JavaScript

function loadModal(id) {
    //load the modal
    var modal = document.getElementById("myModal");
    var btn = document.getElementById("editLink");
    var span = document.getElementsByClassName("close")[0];
    var saveBtn = document.getElementById("saveButton");



    //populate the modal with tweet content
    fetch(`/edit/${id}`)
    .then(response => response.json())
    .then(postDetails => {
       
        modal.style.display = "block";
        postDetails.forEach(element => { 
            document.querySelector('#editPostBox').value = `${element.postContent}`;
    })

    })
   
   
    // When the user clicks on <span> (x), close the modal
    span.onclick = function () {
        modal.style.display = "none";
    }

    saveBtn.onclick = function(){
        fetch(`/edit/${id}`, {
            method: 'PUT',
            body: JSON.stringify({
              postContent: document.querySelector('#editPostBox').value
            })
        })
    
        modal.style.display = "none";
    }



    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function (event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
}

HTML

<!--The Modal-->
<div id="myModal" class="modal">

    <!--Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <h4>Edit Your Post</h4>
            <span class="close">&times;</span>
        </div>
        <div class="modal-body">
                <textarea name="editPostBox" id="editPostBox"></textarea>
                <button class="saveButton" id="saveButton" type="submit" >Save</button> 
            </div>
    </div>
</div>

<!--Modal for Editing Tweets - End-->

<div class="firstSection">
    <div class="container">
        <div class="card">
            <form method="POST">{% csrf_token %}
                <textarea name="newPostBox" id="newPostBox" placeholder="What's happening?"></textarea>
                <button class="btn btn-primary" type="submit" id="postButton" onclick='newPostFunc();'>Tweet</button>
            </form>
        </div>
    </div>
</div>


{% for d in page_obj %}
<div class="secondSection">
    <div class="container">
        <div class="card">
            <h4><a href="profile/{{d.created_by}}" class="userNameClick">{{d.created_by}}</a></h4>
            <a href="#" onclick="loadModal('{{d.id}}');" id="editLink">Edit</a>
            <p>{{d.postContent}}</p>
            <small>{{d.dateAndTime}}</small>
            <small>Likes</small>
        </div>
    </div>
    {% endfor %}

獲取后,您可以選擇明信片元素並更改其內部文本。 這是我的解決方案。

  1. HTML:應該有第二部分中卡片的每個ID,以便我們可以通過其ID選擇卡片元素。 並添加 p 標記(將呈現內容)id 或 class 以便我們可以找到此元素並更改其內部文本
<div class="secondSection">
    <div class="container">
        <div class="card" id="d.id">
            <h4><a href="profile/{{d.created_by}}" class="userNameClick">{{d.created_by}}</a></h4>
            <a href="#" onclick="loadModal('{{d.id}}');" id="editLink">Edit</a>
            <p id="contents">{{d.postContent}}</p>
            <small>{{d.dateAndTime}}</small>
            <small>Likes</small>
        </div>
    </div>
  1. JavaScript:獲取后,您可以通過它的id選擇卡片元素,然后在卡片元素的子元素中,找到'p標簽'(渲染帖子的內容),然后更新它的內部文本。
    saveBtn.onclick = function(){
        const updatedValue =document.querySelector('#editPostBox').value;
        fetch(`/edit/${id}`, {
            method: 'PUT',
            body: JSON.stringify({
              postContent:updatedValue
            })
        }).then(response=>{
            // if update succeeds in backend
            const updatedCard = document.querySelector(`# SpecificCard Id `);
            const children = updatedCard.children; // find children elements all
            for(let i = 0 ; i < children.length; i ++ ){
                if(children[i].id==='contents'){ // find contents p tag 
                    children[i].innerText=updatedValue; // change inner text of p tag 
                    return;
                }
            }
            
        }
        )
    
        modal.style.display = "none";
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM