单击编辑按钮时,如何使用数据库值填充HTML表单?

问题描述 投票:0回答:1

我想在单击编辑按钮时使用数据库值填充表单字段。我要填充的表单负责更新日记条目的属性(包括标题和正文)。

目前,当我单击编辑按钮时,我会得到一个空的编辑表单。因此,如果我想保留条目的一些现有信息(例如条目的主体),我必须在更新条目之前将条目的主体复制到编辑表单中,这是一项繁琐的任务。

我该如何实现呢?

更新日记条目的功能

function edit_entry(entry_id){
    // open modal to edit diary entry
    var modal = document.getElementById('edit_modal');

    modal.style.display = "block";

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    };
    document.getElementById('edit_modal').addEventListener('submit', updateDetail);

    function updateDetail(e){
        e.preventDefault();
        let title = document.getElementById('title').value;
        let body = document.getElementById('body').value;

        var statusCode;

        fetch('http://localhost:5000/api/v1/entries/'+parseInt(entry_id),{
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + window.localStorage.getItem('token')
            },
            body: JSON.stringify({
                "title": title,
                "body": body,
            })    
        })
        .then((result) => {    
            statusCode = result.status;
            return result.json();
        })
        .then((data) =>{    
            window.alert(data.message);
            modal.style.display = "none";
            redirect: window.location.replace('./viewAllEntries.html');    
        });    
    }    
}

HTML表单

<form action="" class ="add-content" id="edit_modal">    
    <h2>My Diary | Edit Entry <i class="fa fa-book" aria-hidden="true"></i></h2>

    <div class="form-group">
        <label></label>
        <textarea id = "title" class ="input-control"></textarea>
    </div>

    <div class="form-group">
        <label></label>
        <textarea id = "body" class ="input-control">  </textarea>
    </div>

    <div class ="form-group">
        <label>&nbsp</label>
        <button type = "submit" class ="button button-block" />Save <i class="fa fa-floppy-o" aria-hidden="true"></i></button>
    </div>
</form>
javascript fetch-api
1个回答
1
投票

当您打开模态时,只需从API中获取条目的数据即可。尝试类似下面的代码。

$ yourUrlToFetchTheData应该是api路由的url,用于获取所需的数据。

fetch($yourUrlToFetchTheData, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + window.localStorage.getItem('token')
        }
    })
    .then((result) => {
        // TODO FILL THE TEXTAREAS WITH THE VALUES OF THE RESULT.
        $("title").text(result.json.title);
        $("body").text(result.json.body);

    })
    .then((data) => {
        // TODO DO SOMETHING WITH THE ERROR.
    });

将此代码放在modal.style.display =“block”之后;并稍微修改一下!

© www.soinside.com 2019 - 2024. All rights reserved.