JS에서 어떻게 서버를 요청하는지 : Ajax
Ajax : Ajax는 jQuery를 임포트한 페이지에서만 동작 가능합니다.
Uncaught TypeError: $.ajax is not a function → ajax라는 게 없다는 뜻
Ajax 기본 골격
$.ajax({
type: "GET", // GET 방식으로 요청한다.
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})
Get 방식으로 URL을 요청해서 response를 찍겠다.
$ajax 코드 설명
type: "GET" → GET 방식으로 요청한다.
url: 요청할 url
data: 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
리마인드 GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다. http://naver.com?param=value¶m2=value2 POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다. data: { param: 'value', param2: 'value2' },
success: 성공하면, response 값에 서버의 결과 값을 담아서 함수를 실행한다.
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response)
}
$.ajax({
type: "GET", // GET 방식으로 요청한다.
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})
개발자도구 콘솔에 찍어보기
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function(response){
// 값 중 도봉구의 미세먼지 값만 가져와보기
let dobong = response["RealtimeCityAir"]["row"][11];
let gu_name = dobong['MSRSTE_NM'];
let gu_mise = dobong['IDEX_MVL'];
console.log(gu_name, gu_mise);
}
})
모든 구의 미세먼지 값을 찍어보기
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function (response) {
let mise_list = response["RealtimeCityAir"]["row"];
for (let i = 0; i < mise_list.length; i++) {
let mise = mise_list[i];
let gu_name = mise["MSRSTE_NM"];
let gu_mise = mise["IDEX_MVL"];
console.log(gu_name, gu_mise);
}
}
});
- 이미지 바꾸기 : $("#아이디값").attr("src", 이미지URL);
- 텍스트 바꾸기 : $("#아이디값").text("바꾸고 싶은 텍스트");
'언어공부-프론드엔드 > javascript' 카테고리의 다른 글
| 후발대)forEach,map,filter,reduce,fetch 배운2일차 (0) | 2022.12.05 |
|---|---|
| 후발대)배열,for문 배운 1일차 (0) | 2022.12.05 |
| [1주차]스파르타코딩클럽 - 웹개발 (0) | 2022.07.04 |
| [1주차]스파르타코딩클럽-앱개발 (0) | 2022.06.30 |
| 제로베이스 공부 (0) | 2022.06.27 |