SW/JavaScript

Web, jQuery : 부분 페이지 자동 로드 메소드 : 예제, 구현, 사용 방법

얇은생각 2020. 3. 30. 19:30
반응형

Web, jQuery : 부분 페이지 자동 로드 메소드 : 예제, 구현, 사용 방법

 

jQuery 로드 메소드 사용 방법

jQuery와 PHP를 사용하여 웹 페이지에 RSS 피드를 표시하는 작은 웹 응용 프로그램을 만드는 방법을 배웁니다. 이를 위해 jQuery AJAX 기능을 사용하여 PHP 프록시에서 데이터를 쉽게 가져 와서 웹 페이지에 표시 할 것입니다.

 

 

 

jQuery Ajax 로드 메소드

이 튜토리얼에서는 AJAX Get 함수를 사용하여 파일의 내용을 가져 오는 빠른 방법인 jQuery 로드 메소드를 사용합니다. 그러면 로드 메소드가 1분마다 PHP 페이지의 새 데이터로 자동 실행됩니다. 이 메소드는 URL, 데이터 및 콜백 함수의 3 가지 매개 변수를 사용합니다.

.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )

 

- URL - 요청이 전송되는 URL입니다.
- 데이터 - 사용할 매개 변수로 URL에 전송되는 문자열입니다.
- 콜백 함수 - 요청이 완료 될 때 실행될 함수입니다.

 

 

 

HTML

HTML은 간단합니다. jQuery AJAX 함수의 리턴으로 채울 div가 있습니다.

<div id="feed_result"></div>

 

 

 

PHP

PHP는 클래스 속성에 저장할 생성자 매개 변수로 URL을 얻는 작은 PHP 클래스입니다. 그런 다음 RSS 피드의 내용을 가져 오기 위해 cURL 요청을하는 GetFeed () 메소드를 호출 할 수 있습니다. 그런 다음 RSS 피드의 내용을 반복하여 내용에 대한 div를 만들 수 있습니다. div에 대한 내용이 있으면 내용을 에코하기 만하면 페이지에 표시됩니다. jQuery 로드 메소드를 사용함에 따라 이 PHP 파일을 호출하면 PHP 파일의 내용이 표시됩니다.

<?php

// Create new object and pass in RSS feed URL
$process = new Process_Rss_Feed("http://feeds.feedburner.com/Paulundcouk");

// Call GetFeed Method
$process->GetFeed();

class Process_Rss_Feed{

    private $url = false;

    /**
     * Constructor of the Process RSS Feed class
     * @param url - URL to get Feed
     */
    public function __construct($url){
        $this->url = $url;
    }

    /**
     * Get rss feed
     */
    public function GetFeed(){  
        //Initialize the Curl  
        $ch = curl_init();  

        //Set curl to return the data instead of printing it to the browser.  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2); 

        //Set the URL  
        curl_setopt($ch, CURLOPT_URL, $this->url);  

        //Execute the fetch  
        $data = curl_exec($ch);  

        //Close the connection  
        curl_close($ch);

        // If data is returned
        if($data != null){
            // Create XML object
            $xml = new SimpleXMLElement($data);

            $result = "";

            // Loop through each of the items and dislay the title and the description
            foreach($xml->channel->item as $item){

                $result .= '<div class="item">';

                    $result .= '<h2>'.(string)$item->title.'</h2>';

                    $result .= '<p>'.(string)$item->description.'</p>';

                $result .= '</div>';    
            }

            echo $result;
        }  
    }
}

?>

 

 

 

jQuery

이 응용 프로그램에 사용하는 jQuery는 다음과 같습니다. jQuery 파일이 로드 될 때 실행되는 다큐먼트 레디 함수가 있습니다. 응용 프로그램의 모든 주요 작업을 수행합니다. 먼저 ajax 기능을 설정하여 시작합니다. 요청을 보내기 전에 모든 ajax 호출에서 feed_result div를 숨기고 요청이 완료되면 feed_result div를 표시하려고합니다.

다음으로 feed_result div에 jQuery 객체를 설정합니다. 이것이 load 메소드를 호출하는 객체입니다. 그러면 load 메소드는 process_rss_feed.php 파일을 호출하여 PHP 파일의 내용에 ajax GET 요청을 보내고 feed_result div에 내용을 로드합니다. 이제 1분 후에 setInterval을 호출하여 div의 컨텐츠를 자동으로 새로 고치는 기능을 추가 할 수 있습니다.

(function($)
{
    /**
     * Run this function on ready of the document
     */
    $(document).ready(function()
    {
        SetupAjax();

        // Create feed result object
        var $result = $("#feed_result");

        // Load the contents of the URL in the result object
        $result.load("process_rss_feed.php");

        // Setup an auto refresh function to run every 30 seconds
        var auto_refresh = setInterval(function()
        {
            $result.load('process_rss_feed.php');
        }, 60000);
    });

    /**
     * Setup the ajax functionality
     */
    function SetupAjax(){
        $.ajaxSetup(
        {
            beforeSend: function() {
                $('#feed_result').hide();
            },
            success: function() {
                $('#feed_result').show();
            }
        });
    }

})(jQuery);
반응형