Front-End/J-Query

jQuery AJAX

jQuery - AJAX Introduction

jQuery AJAX Example - AJAX  서버에서 값 가져오기

What is AJAX?

AJAX = Asynchronous JavaScript and XML.     // 비동기화 한 자바스크립트 그리고 XML
특정 지정된 내용만 불러들이는 기술, 전체를 로드하지 않음
AJAX는 전체 페이지를 다시 로그하지 않고, 백그라운드에서 데이터를 로드하여 웹 페이지에 표시하는 
기능

What About jQuery and AJAX?

jQuery provides several methods for AJAX functionality.
jQuery는 AJAX 기능을 위한 몇 가지 메소드를 제공
jQuery AJAX 메소드를 사용하면 HTTP Get 및 HTTP Post를 사용하여 원격 서버에서 텍스트, HTML, XML 또는 JSON을 요청할 수 있으며 웹페이지의 선택된 HTML 요소에 외부 데이터를 직접 로드 할 수 
있음

jQuery가 없으면 AJAX 코딩이 까다로움

다른 브라우저를 테스트 하기 위해서 추가 코드를 작성해야하는데 jQuery 팀이 이 문제를 처리하여
한줄 코드만으로  AJAX  기능을 작성할수 있음(팩트 폭행)

jQuery - AJAX load() Method

jQuery load() Method

jQuery load() 메서드는 간단하지만 강력한 AJAX 메서드
load() 메서드는 서버에서 데이터를 로드하고 반환 된 데이터를 선택한 요소에 저장

Syntax:
$(selector).load(URL,data,callback);    // (선택자).로드(서버주소,데이터,콜백);

필수 URL 매개 변수는로드하려는 URL을 지정합니다.
선택적 data 매개 변수는 요청과 함께 보낼 쿼리 문자열 키 / 값 쌍의 집합을 지정합니다.
선택적 콜백 매개 변수는 load () 메서드가 완료된 후 실행할 함수의 이름입니다.
예제 파일의 내용은 다음과 같습니다. "demo_test.txt":

demo_test.txt 파일의 내용을 특정 <div> 로드함
Ex)1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt");        // 서버에 있는 txt 내용을 로드함
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

서버에 있는 demo_test.txt 내용 = jQuery and AJAX is FUN!

Ex)2 - 특정 내용만 불러들인다.
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt #p1");    // txt문서에서 id가 p1인 부분만 로드
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>
p1 내용 = <p id="p1">This is some text in a paragraph.</p>

콜백함수 사용
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){    // 콜백함수
            if(statusTxt == "success")            // 문서가 로드가 잘되었으면 success
                alert("External content loaded successfully!");
            if(statusTxt == "error")                // 문서가 로드가 안되었으면 error
                alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

jQuery AJAX Reference

https://www.w3schools.com/jquery/jquery_ref_ajax.asp

jQuery - AJAX get() and post() Methods

HTTP Request: GET vs. POST

  • GET - Requests data from a specified resource                        // 검색결과 url 뒤에 붙음
  • POST - Submits data to be processed to a specified resource   // 비밀번호

jQuery $.get() Method

Syntax:
$.get(URL,callback);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("demo_test.asp", function(data, status){    // 콜백 함수 사용 불러오면 alert
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>

Tip: Here is how the ASP file looks like ("demo_test.asp"):

<%
response.write("This is some text from an external ASP file.")
%>

jQuery $.post() Method

Syntax:

$.post(URL,data,callback);
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.post("demo_test_post.asp",
        {
          name: "Donald Duck",
          city: "Duckburg"
        },
        function(data,status){  // 콜백 함수가 실행 // 콜백은 모든 기능이 끝났을때 기다렸다가 실행
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

Tip: Here is how the ASP file looks like ("demo_test_post.asp"):
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>

jQuery AJAX Reference

https://www.w3schools.com/jquery/jquery_ref_ajax.asp


'Front-End > J-Query' 카테고리의 다른 글

w3schools - templates  (0) 2017.07.06
jQuery Misc  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jquery HTML  (0) 2017.07.06
jQuery Effects  (0) 2017.07.06
,

최근 댓글

최근 트랙백

알림

이 블로그는 구글에서 제공한 크롬에 최적화 되어있고, 네이버에서 제공한 나눔글꼴이 적용되어 있습니다.

태그

카운터

Today :
Yesterday :
Total :