Прикрепить JSON к существующей форме - PullRequest
1 голос
/ 15 апреля 2020

Я извлекаю exif-данные из выбранного изображения в бланке блога для моего личного сайта. Я хотел бы отправить данные exif, найденные в виде поля моей формы, отформатированного как JSON. Я не уверен, что правильный подход к этому. Моей первой мыслью было просто сделать ввод text_area и установить значение JSON в этом поле. Хотя я чувствую, что должен быть лучший путь.

Мысли?

1 Ответ

0 голосов
/ 16 апреля 2020

Вы можете сделать это следующим образом, добавить метаданные изображения в виде поля объекта данных и отправить его:

// The elements are being instanced outside the event listener. In the event listener we can get the current value of the element
const nameInput = document.getElementById('name') 
const lastNameInput = document.getElementById('last-name')
const idInput = document.getElementById('id')

// A regular button, not a submit one
const sendBtn = document.getElementById("send-btn")

// The event that will listen the button, take the data of your fields and send it in JSON format
sendBtn.addEventListener('click', async () => {
    // The URL of your server
    const url = 'http://localhost:3000/users'

    const data = { 
        name: nameInput.value,
        lastName: lastNameInput.value,
        id: idInput.value
    }

    const request = new Request(
        url,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }, // If the headers are not defined, your backend application doesn't recognize the data sent with JSON
            body: JSON.stringify(data)
        }
    )

    try {
        const response = await fetch( request )
        const jsonResponse = await response.json()
        // With the response of the server you have infinite posibilities.
        console.log(jsonResponse)
    } catch (e){
        alert('Error connecting with the server')
    }    
})
...