티스토리 뷰

TIL(Today I Learn)

TIL220509

minji_6119 2022. 5. 10. 07:07

JavaScript

let word = '{{ word }}'
        $(document).ready(function () {
            get_definitions()
        })

        function get_definitions() {
            $.ajax({
                type: "GET",
                url: `https://owlbot.info/api/v4/dictionary/${word}`,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", "Token 1b36aa060c69dc53b4ac8ddedfe38f996274b17a");
                },
                data: {},
                error: function (xhr, status, error) {
                    alert("에러 발생!");
                },
                success: function (response) {
                    $('#word').text(response['word']);

                    let pronunciation = response["pronunciation"];

                    if(pronunciation == null) {
                        $('#pronunciation').text('');
                    } else{
                        $('#pronunciation').text(`/${pronunciation}/`)
                    }

                    let definitions = response['definitions']
                    $('#definitions').empty()
                    for (let i = 0; i < definitions.length; i++) {
                        let type = definitions[i]['type']
                        let def = definitions[i]['definition']
                        let example = definitions[i]['example']

                        let temp_html = ``;
                        if(example == null) {
                            temp_html = `<div style="padding:10px">
                                            <i>${type}</i>
                                            <br>${def}<br>
                                            <span class="example"></span>
                                        </div>`
                        } else {
                            temp_html = `<div style="padding:10px">
                                            <i>${type}</i>
                                            <br>${def}<br>
                                            <span class="example">${example}</span>
                                        </div>`
                        }

                        $('#definitions').append(temp_html)
                    }

                }
            })
        }
@app.route('/detail/<keyword>')
def detail(keyword):
    # API에서 단어 뜻 찾아서 결과 보내기
    return render_template("detail.html", word=keyword)

ajax를 이용하면 새로 고침을 할 때 마다 API에 요청을 받고 다시 html에 채워주기 때문에 시간이 걸린다. 사용자 입장에서는 이가 어색하게 느껴질 수 있으므로 html을 완성하여 보내주는 서버사이드 렌더링을 하는 것이 좋다.

 

jinja2를 이용하여 API 데이터 받아오기

 <div class="container">
        <div class="d-flex justify-content-between align-items-end">
            <div>
                <h1 id="word" style="display: inline;">{{ word }}</h1>
                {% if result.pronunciation %}
                <h5 id="pronunciation" style="display: inline;">/{{ result.pronunciation }}/</h5>
                {% endif %}
            </div>
            <button id="btn-save" class="btn btn-outline-sparta btn-lg">
                <i class="fa fa-floppy-o" aria-hidden="true"></i>
            </button>
            <button id="btn-delete" class="btn btn-sparta btn-lg">
                <i class="fa fa-trash-o" aria-hidden="true"></i>
            </button>
        </div>
        <hr>
        {% for definition in result.definitions %}
            <div style="padding:10px">
                <i>{{ definition['type'] }}</i>
                <br>{{ definition['definition'] }}<br>
                {% if definition.example %}
                <span class="example">{{ definition['example']|safe }}</span>
                {% endif %}
            </div>
        {% endfor %}
    </div>
</div>

JavaScript에서는 Indentation을 고려하지 않으므로

{% if %}를 사용했다면 {% endif %}

{% for %}를 사용했다면 {% for %}

 

리스트의 값을 가져올 때 result['pronunciation']도 가능하지만, result.pronunciaion도 가능.

 

definition.example | safe 는 html 태그들이 string으로 프린트 되는 것을 방지

 

MongoDB 지속적인 오류 발생

-> 웹 플러스 강의 1주차를 듣지 않아 생긴 문제

 

현재까지 해결하지 못하고 있는 오류, mongodb+srv로 변경해서 진행중

'TIL(Today I Learn)' 카테고리의 다른 글

TIL 220517  (0) 2022.05.18
WIL 1주차(Week I Learn)  (0) 2022.05.16
TIL220511  (0) 2022.05.12
TIL220511  (0) 2022.05.11
TIL220510  (0) 2022.05.10
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함