How to send json to server?

  • 0
    Good afternoon, I have a json string.
    let map= new Map([["80-c4-48-84-79", " Federal research and production center "],
    ["73-b3-49-af-9d"," dgru"],
    ["04-d2-45-86-6a","Main"],
    ["d0-51-41-bf-4f", " Publications"],
    ["c5-3c-4d-83-4f", " news"],
    ["7d-ae-46-a0-25", "Contacts"],
    ["8f-01-4b-81-4e", "Certification center"],
    ["56-32-40-82-1a","1959"],
    ["27-63-47-b9-1c","2019"],
    ["a7-34-46-b8-38"," Moscow"],
    ["42-29-4c-bb-df"," text"],
    ["67-8b-47-b1-34","example"]]);
    
    const result = JSON.stringify({ room: Object.fromEntries(map) });
    console.log(result)


    Result
    {"room":{"80-c4-48-84-79":" Federal research and production center ","73-b3-49-af-9d":" dgru","04-d2-45-86-6a":"Main","d0-51-41-bf-4f":" Publications","c5-3c-4d-83-4f":" news","7d-ae-46-a0-25":"Contacts","8f-01-4b-81-4e":"Certification center","56-32-40-82-1a":"1959","27-63-47-b9-1c":"2019","a7-34-46-b8-38":" Moscow","42-29-4c-bb-df":" text","67-8b-47-b1-34":"example"}}


    How do I send json to the server?

    I do this, but my request is not being sent. Help fix
    let map= new Map([["80-c4-48-84-79", " Federal research and production center "],
    ["73-b3-49-af-9d"," dgru"],
    ["04-d2-45-86-6a","Main"],
    ["d0-51-41-bf-4f", " Publications"],
    ["c5-3c-4d-83-4f", " news"],
    ["7d-ae-46-a0-25", "Contacts"],
    ["8f-01-4b-81-4e", "Certification center"],
    ["56-32-40-82-1a","1959"],
    ["27-63-47-b9-1c","2019"],
    ["a7-34-46-b8-38"," Moscow"],
    ["42-29-4c-bb-df"," text"],
    ["67-8b-47-b1-34","example"]]);
    let names;
    let slovo;
    console.log(translateText())
    
    const result = JSON.stringify({ room: Object.fromEntries(map) });
    console.log(result)
    
    
    function translateText(result) {
        var xhr = new XMLHttpRequest();
       
        //console.log(s)
        let url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&hl=ru&dt=t&dt=bd&dj=1&source=icon&tk=467103.467103&q=';
        console.log(url)
        xhr.open('GET', url, true);
        xhr.send(result);
        if (xhr.status != 200) {
            // обработать ошибку
            alert(xhr.status + ': ' + xhr.statusText); // пример вывода: 404: Not Found
        } else {
            // вывести результат
            names = xhr.responseText;
            let data = JSON.parse(xhr.responseText);
            slovo = data.sentences[0].trans;
            
        }
        return slovo;


    The link from the Google translate remained from the examples. There will be another link there. The very fact that the request with json is not sent
    JavaScript Sophie Choi, Jan 20, 2020

  • 1 Answers
  • 0
    1) You are making an asynchronous request, it has several states. We need the 4th. For this, we will redo the translateText function.

    function translateText() {
    var xhr = new XMLHttpRequest();
    var url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&hl=ru&dt=t&dt=bd&dj=1&source=icon&tk=467103.467103&q=';

    xhr.open('POST', url, true);
    xhr.send(result);

    xhr.onreadystatechange = function () { // (3)
    if (xhr.readyState != 4) return;

    if (xhr.status != 200) {
    // обработать ошибку
    alert(xhr.status + ': ' + xhr.statusText); // пример вывода: 404: Not Found
    } else {
    // вывести результат
    names = xhr.responseText;
    console.log( JSON.parse(xhr.responseText) );
    }
    }
    }




    2) There is no sentences array in the response, so slovo = data.sentences [0] .trans will throw an exception.



    3) console.log (translateText ()) won't work, because console.log will not wait for the complete execution of the request. Therefore, you need to shove it into the function itself.



    4) XHR has modern asynchronous counterparts like fetch

    function translateText() {
    let url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&hl=ru&dt=t&dt=bd&dj=1&source=icon&tk=467103.467103&q=';
    fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    body: JSON.stringify({ room: Object.fromEntries(map) })
    })
    .then(response => response.ok ? response.json() : response.status)
    .then(result => console.log(result));

    /*
    Выполняем запрос. Далее если он усешен, распаршиваем его, в ином случае передаем статус.
    Далее выводим это в консоль.
    */
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!