Programmer's Progress

Ajax 를 이용한 교차 도메인 XML 데이터 Binding 하기 본문

JavaScript + JQuery/Self Learning

Ajax 를 이용한 교차 도메인 XML 데이터 Binding 하기

Blanc et Noir 2021. 2. 10. 21:04

JavaScript에는 동일 출처의 원칙(Same-Origin Policy)이라는 것이 존재한다. 이는 같은 도메인을 지닌 사이트 간의

데이터 송수신 작업은 가능하지만, 도메인이 서로 다른 사이트 간 데이터 송수신 작업은 불가하다는 것을 말한다.

이는 잠재적으로 해로울 수 있는 문서를 분리하여 보안성을 확보하기 위함이라 한다.

 

그렇다면 언론 사이트나, 기상청 같은 다른 사이트에서 제공하는 데이터를 JavaScript에서 전혀 활용할 수 없느냐

하고 묻는다면, 대답은 No라고 말할 수 있다. 서버 스크립트 페이지 언어를 사용하면 교차 도메인을 활용해서 XML 데이터를 얻을 수 있다. 그리고 나는 PHP를 활용해보려 한다.

 

HTML : Source Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="domain - 2.css">
    <script src="jquery.js"></script>
    <script src="jquery-ui.js"></script>
    <script src="domain - 2.js"></script>
    <title>Document</title>
</head>
<body>
    <div id="wrapper"></div>
</body>
</html>

 

CSS : Source Code

table{
    border-collapse: collapse;
}
th{
    background-color: #ccc;
    padding: 10px;
}
tr:nth-of-type(2n){
    background-color: #eee;
}
td{
    padding: 10px;
}

 

JavaScript : Source Code

$(document).ready(function(){
    $.ajax({
        "url" : "domain - 2.php",
        "dataType" : "xml",
        "success" : function(result){
            var db = $(result).find("city:contains('횡성')").nextAll("data");
            var time, weather, min, max, rain, tb, tr;
            time = $("<th />").text("시간");
            weather = $("<th />").text("날씨");
            min = $("<th />").text("최저온도");
            max = $("<th />").text("최고온도");
            rain = $("<th />").text("강수확률");
            tr = $("<tr />").append(time, weather, min, max, rain);
            tb = $("<table />").append(tr);
            var i;
            for(i=0; i<10; i++){
                console.log(i*(-1));
            }
            $.each(db,function(index,obj){
                console.log(index);
                time = $("<td />").text($(obj).find("tmEf").text());
                weather = $("<td />").text($(obj).find("wf").text());
                min = $("<td />").text($(obj).find("tmn").text());
                max = $("<td />").text($(obj).find("tmx").text());
                rain = $("<td />").text($(obj).find("rnSt").text());
                tr = $("<tr />").append(time,weather,min,max,rain);
                tb.append(tr);
            });
            $("#wrapper").append(tb);
        },
        "error" : function(){
            alert("ERROR");
        },
        "complete" : function(){
        }
    })
});

 

PHP : Source Code

<?php
    $session = curl_init();
    curl_setopt($session,CURLOPT_URL,"http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=105");
    curl_setopt($session,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($session,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($session,CURLOPT_HEADER,0);
    $result = curl_exec($session);
    curl_close($session);
    echo $result;
?>

 

PHP를 배워본 적은 없고, 공부하는 책에 나온 소스코드를 읽고 분석하며 이해하려 했다. 사실 이해라고 해도

세션을 열기 전에 URL이나 SSL유효성 검사 등의 옵션을 설정하고 세션을 실행시키면 XML 데이터를 전부 읽어와서

$result변수에 담고, 이 과정이 끝나면 세션을 종료한다...... 이 정도로 이해하고 있을 뿐이다.

Binding 하려는 XML 데이터는 기상청에서 제공하는 날씨정보다.

 

소스코드를 실행시키면 다음과 같은 화면이 나타난다.

내가 사는 지역은 2월 15일 자정부터 낮까지 비가 좀 오려나 보다... 하고 알게 되었다.

RSS(Really Simple Syndication)이라는 기술이 참 편리하긴 한 것 같다.

처음 네이버에서 블로그를 운영할 때는 블로그 관리할 때 RSS설정이 대체 뭐야? 하고 그냥 넘긴 적이 많았는데

이런 곳에서 사용할 수 있구나 하고 배워가는 게 재밌었다.

다음에는 JSONP를 이용한 교차 도메인 Binding을 배워봐야겠다.

Document (dothome.co.kr)

 

Document

 

jrw9215.dothome.co.kr

 

Comments