AJAX using JQuery
-form을 이용한 jQuery AJAX 요청
$('#f').on('submit',function(e){
/*let parameter1=$('#f').serialize();
console.log(parameter1);*/
let parameter2 = $(e.target).serialize();
let jsonArray = $(e.target).serializeArray();
e.preventDefault();
});
form.on('submit',function)
form에 submit 이벤트 리스너 등록
>form의 input parameters (json data) 생성
++('#f') 폼으로 접근하는것은 권장하지 않는다.
이벤트가 발생한 event target으로 접근
let parameter2 = $(e.target).serialize();
serialize() 함수 => property=value&property=value&... 형식으로 data 생성
let jsonArray = $(e.target).serializeArray();
serializeArray() 함수 =>json 배열 형태로 data 생성
++element의 속성값 접근하기
//attribute set
$('#p_image').attr('src','icon1.png');
//attribute get
console.log($('#p_image').attr('src'));
attr('attributeName'[,value])
++폼 태그의 입력값에 접근할 때
console.log("1.$('#id').attr('value') [x]:"+$('#id').attr('value'));
console.log("1.$('#id').val() [o]:"+$('#id').val());
attr('value') value 속성의 값에 접근하는 방법은 사용하지 않는다.
val() 함수를 사용하면 DOM 생성 이후 동적으로 변하는 value 값을 읽을 수 있다.
>jQuery AJAX 요청
$.ajax(url[, settings])
settings type = plainObject == json == { url:xx, setting1:xx, setting2:xx...}
ㅁ settings
method: type(String) default('GET')
Http요청 보낼 방식
contentType: type(boolean or String) default('application/x-www-form-urlencoded; charset=UTF-8')
서버로 데이터를 보낼 때 데이터의 타입 : multipart/form-data, text/plain...
data: type(plainObject or String or Array) default({})
서버로 보낼 데이터
body를 가질 수 없는 requestMethod(GET) 의 경우 data가 URL에 붙여진다.
dataType: type(String) default(jquery가 xml, json, script, html 중 적절한 타입을 찾아 설정, 보통 json)
서버로부터 받은 응답의 데이터 타입
timeout: type(number) default(0)
number ms 만큼 timeout 한 후에야 send 된다.
statusCode: type(PlainObject==json) default({})
응답의 상태 코드
요청이 성공적으로 이루어지면 success callback
3xx(redirect)를 포함한 4xx,5xx(error) 발생시 error callback
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
404 코드일때 function() 실행
beforeSend: type(function(jqxhr,settings{})
요청 전 실행될 함수
success: type(function(data, textStatus, jqxhr))
요청 성공시 실행될 함수
error: type(function(jqxhr,textStatus,errorThrown))
error 발생시 실행될 함수
complete: type(function(jqxhr, textStatus))
success, error callback 함수가 실행된 이후 실행될 함수
$.ajax({
url:`01.ajaxRequestPOST/${idStr}`,
method:`POST`,
data: parameter 또는 jsonArray,
contentType:'application/json;charset=UTF-8',
dataType:'json',
success:function(responseJsonObject){
...
},
});
>prevent default submit
e.preventDefault();
GET 방식 AJAX 요청 예제
$('#id').keyup(function (e) {
let idStr = $(e.target).val();
if (idStr.trim() == '') return;
$.ajax({
url: `01.ajaxRequestGET/${idStr}`,
method: `GET`,
data: {},
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
success: function (responseJsonObject) {
if (responseJsonObject.status == 1) {
$('#msg').html(responseJsonObject.msg).css('color', 'green');
} else if (responseJsonObject.status == 2) {
$('#msg').html(responseJsonObject.msg).css('color', 'orange');
}
},
error: function (xhr, textStatus) {
alert('error!!' + textStatus);
}
})
});
keyup 이벤트가 발생할 때 입력된 값을 받고 ajax 요청을 한다. url로 id를 맵핑하기 때문에 data가 필요없다.
POST 방식 AJAX 요청 예제
$.ajax({
url:`01.ajaxRequestPOST/${idStr}`,
method:`POST`,
data:{},
contentType:'application/json;charset=UTF-8',
dataType:'json',
beforeSend:function(){
$('#msg').html('<img src="loading.gif" width="20px" height="20px/>');
},
success:function(responseJsonObject){
if(responseJsonObject.status==1){
$('#msg').html(responseJsonObject.msg).css('color','green');
}else if(responseJsonObject.status==2){
$('#msg').html(responseJsonObject.msg).css('color','orange');
}
},
error:function(xhr,textStatus){
alert('error!!'+textStatus);
}
});
beforeSend 함수도 만들어주어 send 직전부터 response를 받을때까지 실행할 함수를 등록
setInterval 함수를 이용하여 정해진 시간 간격마다 AJAX 요청 실행
$(function(){
setInterval(function(){
$.ajax({
url:'04.newsTitlesJSON',
method:'GET',
dataType:'json',
success:function(responseJsonObject){
let html= `<ul>`;
$.each(responseJsonObject.data,function(i,newsJsonObject){
html+=`<li>${newsJsonObject.title}[${newsJsonObject.company}]${newsJsonObject.date}</li><br>`;
});
html+=`</ul>`;
$('#newsDiv').html(html);
}
});
},1000);
})
jQuery API document
https://api.jquery.com/jquery.ajax/
jQuery.ajax() | jQuery API Documentation
Description: Perform an asynchronous HTTP (Ajax) request. The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available
api.jquery.com