채택완료

ajax 새로 고침 질문

안녕하세요

 

 

<div  id="load_tweets"></div>

 

    <script type="text/javascript">
    var auto_refresh = setInterval(
    function ()
    {
    $('#load_tweets').load('<?php echo G5_THEME_URL?>/refresh.html').fadeIn("slow");
    }, 1000); // 새로고침 시간 1000은 1초를 의미합니다.
    </script>
 

 

이런식으로 ajax를 통해 새로고침을 하고 있습니다.

한페이지에 6개 정도의 div 에 적용해놨는데요

 

서버에 무리? 가 가지않는 건지 궁금합니다.

 

1초 말고 내용이 바뀔때마다 갱신되는 방법은 없는건지요?

 

ajax가 처음이라.. 저 방식이 맞는건지 궁금합니다...

|

답변 2개

채택된 답변
+20 포인트

제가 사용하고 있는 소스 입니다.

저도 예전에 구글링해서 얻은 소스라서 서버에 크게 무리는 안가는데요

트위터나 sns 에서 데이터를 못받아올경우 예외처리가 필요해 보입니다.

 

ajax.php ------------------------

이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>

<div id="xx"> XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX </div>
<pre id="yy"> YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY </pre>

이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>
이 페이지가 다시 로딩되는지 확인해야 함<br>

<script language="javascript">
<!--

// 자동으로 일정 시간마다 호출하기..
setTimeout(callFunc, 2000);

function callFunc()
{
        // 잘 작동함 
      AJAX_GET("http://192.168.0.222:7777/ems/xx/test.php", str_callback);

        // 잘 작동함 - 다량의 값을 넘길 때 사용함 
        var     data = {};
        data.xx = "XX데이터";
        data.yy = "YY데이터";
//      AJAX_POST("http://192.168.0.222:7777/ems/xx/test.php", data, str_callback);

        // 잘 작동함 
 //       AJAX_GET("http://192.168.0.222:7777/ems/xx/json.php", json_callback);

        setTimeout(callFunc, 2000);
}

function str_callback(str)
{
        document.getElementById("xx").innerHTML = str;
        document.getElementById("yy").innerHTML = str;
}

/**
* Makes an AJAX call. It calls the given callback (a function) when ready

* @param string   url      The URL to retrieve
* @param function callback A function that is called when the response is ready, there's an example below
*                          called "myCallback".
*/
function AJAX_GET(url, callback)
{
        // Mozilla, Safari, ...
        if (window.XMLHttpRequest) {
            var httpRequest = new XMLHttpRequest();

        // MSIE
        } else if (window.ActiveXObject) {
            var httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }

        httpRequest.onreadystatechange = function ()
        {
            if (this.readyState == 4 && this.status == 200) {
                this.__user_callback__ = callback;
                this.__user_callback__(this.responseText);
            }
        }

        httpRequest.open('GET', url, true);
        httpRequest.send();
};

 


/**
* Makes an AJAX POST request. It calls the given callback (a function) when ready

* @param string   url      The URL to retrieve
* @param object   data     The POST data
* @param function callback A function that is called when the response is ready, there's an example below
*                          called "myCallback".
*/
function AJAX_POST(url, data, callback)
{
        // Used when building the POST string
        var crumbs = [];

        // Mozilla, Safari, ...
        if (window.XMLHttpRequest) {
            var httpRequest = new XMLHttpRequest();
        // MSIE
        } else if (window.ActiveXObject) {
            var httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }

        httpRequest.onreadystatechange = function ()
        {
            if (this.readyState == 4 && this.status == 200) {
                this.__user_callback__ = callback;
                this.__user_callback__(this.responseText);
            }
        }

        httpRequest.open('POST', url, true);
        httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");

        for (ii in data) {
            if (typeof ii == 'string') {
                crumbs.push(ii + '=' + encodeURIComponent(data[ii]));
            }
        }

        httpRequest.send(crumbs.join('&'));
}


//
// PHP에서 보낸 Array가 JSON 포맷으로 변환되어 javascript에서 access가능함 
//
function json_callback(str)
{
        str = decodeURIComponent(str);
//      alert('callback=' + str);

        var obj = JSON.parse(str, null);
        if (obj.info)
                document.getElementById("xx").innerHTML = obj.info;
        if (obj.date)
                document.getElementById("yy").innerHTML = obj.date + " " + obj.array[1];
}

-->
</script>

 

 

test.php -------------------------------------​



 

 

 

 

<?

GLOBAL  $xx, $yy;

srand();
echo "LJM" . rand()." $xx $yy";

?>

json.php ----------------------------------------

​ 

<?

$date = date("Y-m-d H:i:s");

$ar = Array("info" => "AJAX JSON 테스트", 
                "date" => $date, 
                "bb" =>22, 
                "ccc" =>333, 
                "dddd" =>4444, 
                "array" => Array( 1, "2번째", 3, 4, 5, null, 6) );

$ar = euckr2utf8($ar);
echo json_encode($ar, "js");

exit;


//
// EUC-KR 문자열이 들어간 array를 UTF-8로 변경하기 
//
function euckr2utf8($ar, $opt = "")
{
        if (!is_array($ar))
                return mb_convert_encoding($ar, 'UTF-8', 'EUC-KR');

        foreach ($ar as $idx => $value)
        {
                // Javascript 치환 
                if (!is_array($value) && strstr($opt, "js") != "")
                        $ar[$idx] = ($value);
                else
                        $ar[$idx] = euckr2utf8($value, $opt);
        }

        return $ar;
}

/***
echo <<< END_HTML
{
"info":{"maptype":"all", "root_id":"G1"},
"node":[{"nodeid":"G39", "icon":"worldwide_n"},
        {"nodeid":"G102", "icon":"workgroup"}]
}
END_HTML;
***/

?>

내용이 바뀔때마다는 ajax 방식으로 불가능합니다.
node.js나 웹소켓, 웹푸시등의 양방향 통신이 가능한 것들로 구현하셔야 합니다

답변을 작성하려면 로그인이 필요합니다.