Self Code Review/(sparta) WEB plus - 나만의 단어장

[나만의 단어장] 5. 상세페이지 - Ajax로 단어 뜻 가져오기

밍굥잉 2022. 5. 4. 13:06

Ajax 기본 골격

$.ajax({
  type: "GET", //GET 방식으로 요청
  url: "여기에URL을입력", //요청할 url
  data: {}, //요청하면서 함께 줄 데이터 (GET 요청 시엔 비워둠)
  success: function(response){ //성공하면, response 값에 서버의 결과 값을 담아서 함수 실행
    console.log(response) 
  }
})

 

html에서 단어 뜻 보여주기

 

 API에서 단어 뜻 찾아서 결과 보내주기

@app.route('/detail/<keyword>')
def detail(keyword):
    # API에서 단어 뜻 찾아서 결과 보내기
    return render_template("detail.html", word=keyword)
		# <keyword>를 detail.html에 word라는 이름으로 보내주세요

 

 Owlbot API 요청 Ajax

let word = '{{ word }}' //app.py의 detail 함수에서 {{ word }}라는 이름으로 온 것을 변수 word 라고 정의.
$(document).ready(function () {
    get_definitions()
}) //페이지가 로딩되면 get_definitions 함수를 실행.

function get_definitions() {
    $.ajax({
        type: "GET", //GET 방식으로 요청
        url: `https://owlbot.info/api/v4/dictionary/${word}`, //${word}에 해당하는 단어의 뜻을 요청
        beforeSend: function (xhr) { 
            xhr.setRequestHeader("Authorization", "Token [내토큰]");
        }, //요청 보내기 전, 내 토큰에 대한 허가 받기
        data: {},
        error: function (xhr, status, error) {
            alert("에러 발생!");
        }, //에러 발생으로 정보를 가져오지 못할 경우, '에러 발생' 창 띄우기
        success: function (response) {
            console.log(response)
        } //성공하면 response 함수 실행
    })
}

 

 ⬆️ respose 함수

$("#word").text(response["word"]) //id가 word인 div에 word의 형태로 결과값을 넘겨줌
$("#pronunciation").text(`/${response["pronunciation"]}/`) //id가 pronunciation인 div에 /pronunciation/의 형태로 결과값을 넘겨줌
$("#definitions").empty() //먼저 id가 definitions인 div를 비워줌
let definitions = response["definitions"] //definitions라는 변수에 definitions를 선언
for (let i=0;i<definitions.length;i++) { //i가 0부터 시작해서 definitions의 길이보다 짧은 동안 i씩 증가하는 반복문 
    let definition = definitions[i] //definition은 definitions의 i번째 요소
    let html_temp = `<div style="padding:10px"> 
                        <i>${definition["type"]}</i> //품사는 definition의 type
                        <br>${definition["definition"]}<br> //뜻은 definition의 definition
                        <span class="example">${definition["example"]}</span> //예문은 definition의 example
                    </div>`
    $("#definitions").append(html_temp) //id가 definitions인 div에 html_temp를 넣기
}
$("#id").text(response["형태"])

 

 

 ⬆️ 발음이 null일 경우 빈 텍스트

if (response["pronunciation"]==null) { //만약 pronunciation이 null이면
    $("#pronunciation").text("") //id가 pronunciation인 div에 빈 텍스트를 줌
} else { //아니면
    $("#pronunciation").text(`/${response["pronunciation"]}/`) //id가 pronunciation인 div에 /pronunciation/의 형태로 결과값을 넘겨줌
}

 

 

 ⬆️ 예문이 null일 경우 예외처리

let html_temp = ``  //html_temp를 선언하고 비워둠
if (definition["example"]!=null) { //만약 definition의 example이 null이 아니면 (예문이 있으면)
    html_temp = `<div style="padding:10px"> 
                    <i>${definition["type"]}</i>
                    <br>${definition["definition"]}<br>
                    <span class="example">${definition["example"]}</span>
                </div>` //html_temp에 definition의 type, definition, example을 넣음.
} else { //아니면 (예문이 없으면
    html_temp = `<div style="padding:10px">
                    <i>${definition["type"]}</i>
                    <br>${definition["definition"]}<br>
                </div>`
} //html_temp에 definition의 type, definition을 넣음.

$("#definitions").append(html_temp)
  • Owlbot 요청 Ajax를 이용해 단어의 정보를 가져오는데, 발음 또는 예문이 null일 경우 예외처리를 해서 들고 옴.

 

결과

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 [내토큰]");
        }, 
        data: {},
        error: function (xhr, status, error) {
            alert("에러 발생!");
        }, 
        success: function (response) {
            $("#word").text(response["word"]) 
						
            if (response["pronunciation"]==null) { 
                $("#pronunciation").text("") 
            } else { //아니면
                $("#pronunciation").text(`/${response["pronunciation"]}/`) 
            }

            $("#definitions").empty() 
            let definitions = response["definitions"] 
            for (let i=0;i<definitions.length;i++) {  
                let definition = definitions[i] 
                let html_temp = ``  
                    if (definition["example"]!=null) { 
                        html_temp = `<div style="padding:10px"> 
                                        <i>${definition["type"]}</i>
                                        <br>${definition["definition"]}<br>
                                        <span class="example">${definition["example"]}</span>
                                    </div>` 
                    } else { 
                        html_temp = `<div style="padding:10px">
                                        <i>${definition["type"]}</i>
                                        <br>${definition["definition"]}<br>
                                    </div>`
                    } 

                    $("#definitions").append(html_temp)
            }
}
})
}