Как использовать запрос в javascript, чтобы получить изображение с веб-сайта / API и отобразить его с помощью img sr c в html? - PullRequest
0 голосов
/ 19 апреля 2020

Цель кода - взять страну, которую вводит человек, т.е. элемент [4], из массива, добавить страну в URL, а затем использовать запрос для получения изображения из этого URL. Я предположил, что мне нужно использовать img sr c для отображения изображения на моем сайте. Что я делаю не так? Я ничего не вижу. Также я пытаюсь использовать javascript для выполнения sh. Спасибо! API: https://www.countryflags.io

personInfo. html

  <!DOCTYPE html>
        <html lang="en">

        <head>
            <meta charset="UTF-8">
            <title> Person Information Page </title>
            <style>
                h2{
                text-align: center;
                }
                label {
                    display: inline-block;
                    width: 150px;
                    text-align: left;
                }​
            </style>
        </head>

        <body>
        <p style="text-decoration: underline;"><a href=http://127.0.0.1:5000/> Back to home </a></p>
        <h2 id="displayName" ></h2>
        <div class="block">
            <label>Born on: </label>
            <p id="birthdate"></p>
        </div>
        <div class="block">
            <label>Born in the country: </label>
            <p id="country"></p>
        </div>
        <div class="block">
            <label>Some facts about country: </label>
            <img id="countryFlag" src = country_flag; />
        </div>

        <script>


        var personInfoList = JSON.parse(sessionStorage.getItem("newList1"));
                    for(let item of personInfoList) {
                         document.getElementById("displayName").innerHTML = item[0] + " " + item[1];
                         document.getElementById("birthdate").innerHTML = item[2];
                         document.getElementById("country").innerHTML = item[3];
                         const request = new Request('https://www.countryflags.io/{}/shiny/64.png'.format(item[4]), method: 'GET');
                         const URL = request.url;
                         fetch(request)
                          .then(response => {
                            if (response.status === 200) {
                              country_flag = 'https://www.countryflags.io/{}/shiny/64.png'.format(item[4]);
                              document.getElementById("countryFlag").src = country_flag;
                              return response.json();

                            } else {
                              throw new Error('Something went wrong on api server!');
                            }
                          })
                          .then(response => {
                            console.debug(response);
                            // ...
                          }).catch(error => {
                            console.error(error);
                          });

                         //request.args.get(country_flag);
                       }


        </script>
        </body>
        </html>

add_name. html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Add Name Page </title>
    <style>
        body {
            text-align: center;
        }
        form {
            position:relative;
            top:20px;
            display: inline-block;
        }
        label {
            display: inline-block;
            width: 150px;
            text-align: left;
        }​
        p {
            position: relative;
            top: -43px;
            left: 410px;
        }

    </style>

    {% extends "navigation.html" %}
    {% block content %}

</head>
    <body>
         <form action="home.html" >

         <div class="block">
            <label>First name: </label>
            <input type='text' input name='firstname' id='firstname'>
         </div>

         <div class="block">
            <label>Last name: </label>
            <input type='text' input name='lastname' id='lastname'>
         </div>

         <div class="block">
            <label>Birthday: </label>
            <input type='text' input name='birthday' id='birthday' placeholder="mm/dd/yyyy">
         </div>

        <div class="block">
            <label>Country of Origin: </label>
            <input type='text' input name='countryOfOrigin' id='countryOfOrigin'>
        </div>
        <p>
        <input type="button" id="add" value="Submit" onclick= "passVal(); window.location.href = '/';">
        </p>
        </form>

        <script>
        function passVal() {
        var prevValue = localStorage.getItem("newList1");
        var newList;
        if(prevValue) {
            newList = JSON.parse(prevValue);
        } else {

        }
        var newFirstName = document.getElementById("firstname").value;
        var newLastName = document.getElementById("lastname").value;
        var newBirthday = document.getElementById("birthday").value;
        var newCOO = document.getElementById("countryOfOrigin").value;
        newList.push([newFirstName, newLastName, newBirthday, newCOO]);
        sessionStorage.setItem("newList1", JSON.stringify(newList)); }

        </script>

    </body>
    {% endblock %}
</html>

1 Ответ

1 голос
/ 19 апреля 2020

Попробуйте это: personInfo. html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title> Person Information Page </title>
    <style>
        h2{
        text-align: center;
        }
        label {
            display: inline-block;
            width: 150px;
            text-align: left;
        }​
    </style>
</head>

<body>
<p style="text-decoration: underline;"><a href=http://127.0.0.1:5000/> Back to home </a></p>
<h2 id="displayName" ></h2>
<div class="block">
    <label>Born on: </label>
    <p id="birthdate"></p>
</div>
<div class="block">
    <label>Born in the country: </label>
    <p id="country"></p>
</div>
<div class="block">
    <label>Some facts about country: </label>
    <img id="countryFlag" src = country_flag; />
</div>

<script>


var personInfoList = JSON.parse(sessionStorage.getItem("newList1"));
            for(let item of personInfoList) {
                 document.getElementById("displayName").innerHTML = item[0] + " " + item[1];
                 document.getElementById("birthdate").innerHTML = item[2];
                 document.getElementById("country").innerHTML = item[3];

                 country_flag = `https://www.countryflags.io/${item[3]}/shiny/64.png`;
                 document.getElementById("countryFlag").src = country_flag;

               }


</script>
</body>
</html>

add_name. html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Add Name Page </title>
<style>
    body {
        text-align: center;
    }
    form {
        position:relative;
        top:20px;
        display: inline-block;
    }
    label {
        display: inline-block;
        width: 150px;
        text-align: left;
    }​
    p {
        position: relative;
        top: -43px;
        left: 410px;
    }

</style>

{% extends "navigation.html" %}
{% block content %}

 </head>
<body>
     <form action="home.html" >

     <div class="block">
        <label>First name: </label>
        <input type='text' input name='firstname' id='firstname'>
     </div>

     <div class="block">
        <label>Last name: </label>
        <input type='text' input name='lastname' id='lastname'>
     </div>

     <div class="block">
        <label>Birthday: </label>
        <input type='text' input name='birthday' id='birthday' placeholder="mm/dd/yyyy">
     </div>

    <div class="block">
        <label>Country of Origin: </label>
        <input type='text' input name='countryOfOrigin' id='countryOfOrigin'>
    </div>
    <p>
    <input type="button" id="add" value="Submit" onclick= "passVal(); window.location.href = '/';">
    </p>
    </form>

    <script>
    function passVal() {
    var prevValue = localStorage.getItem("newList1");
    var newList = []
    if(prevValue) {
        newList = JSON.parse(prevValue);
    } 
    var newFirstName = document.getElementById("firstname").value;
    var newLastName = document.getElementById("lastname").value;
    var newBirthday = document.getElementById("birthday").value;
    var newCOO = document.getElementById("countryOfOrigin").value;
    newList.push([newFirstName, newLastName, newBirthday, newCOO]);
    sessionStorage.setItem("newList1", JSON.stringify(newList)); }

    </script>

</body>
{% endblock %}

В add_name. html У меня есть изменение "var newList;" в "var newList = []". В personInfo. html нет необходимости извлекать изображение, просто назначьте путь к sr c, и он будет работать.

...