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

How do I populate HTML form with database values when I click edit button?

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

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

我该如何实施?

更新日记条目的功能

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>

当您打开模式时,只需从 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";之后,稍微修改一下!