본문 바로가기

개발기술/프론트엔드

자바스크립트 Browser API

개발환경

크롬 브라우저

  • console : 한줄의 javascript를 바로 동작시킬 수 있는 화면
    • 멀티라인인스트럭션 : shift + enter
  • source - network - arrow click - snippet - new snippet : javascript 파일을 생성하고 Run 시킬 수 있다. 

 

HTML에서 JavaScript를 사용하는 방식

  • 인라인 스크립트 (Inline Script) :
    • <button onclick="alert('Hello, World!')">클릭하세요</button>
  •  내부 스크립트 (Internal Script)
    • <head> <meta charset="UTF-8"> <title>내부 스크립트</title> <script> function showMessage() { alert("안녕하세요!"); } </script> </head>
  • 외부 스크립트 (External Script)
    • JavaScript 코드를 별도의 .js 파일로 작성하고, <script src="파일경로"></script>로 불러오는 방식.
    • CSS와는 달리 <script> 태그의 위치는 <body>의  뒤, 마지막에 위치한다. 이유는, 변경의 대상이 아직 DOM에 입력되지 않으면 null excpetion 문제가 발생하기 때문임.

JavaScript 문법

  • html의 inline javascript로 사용되는 경우 String은 ''으로 표기한다
  • 한줄의 끝에는 ;를 첨가한다

 

 

 

 

JavaScript Tag

예제코드 :

- <input type="button" value="night" onclick="document.querySelctor('body').style.backgroundColor='black';

document.querySelctor('body').style.color='white';">

- <input type="button" value="day" onclick="document.querySelctor('body').style.backgroundColor='white';

document.querySelctor('body').style.color='black';">

 

<input> : 사용자의 입력을 받기위한 개체를 입력하며, 속성값인 type에 따라 다양한 모습을 띈다

- onClickOrOtherAction = "액션에 따라서 동작을 시킬 JavaScriptCode", 이벤트 리스너로 html 속성값으로 약 20개 정도의 이벤트가 정의되어있음.

 

<script> : 동작시킬 JavaScript Code를 입력하는 html태그

 

 

Navigator

function as parameter

fetch then catch

 

 

 

Document  Object Style Property

document.querySelctor(선택자) : 해당 문서에서 특정 선택자에 접근한다.

document.body.style.backgroundColor = "red"

document.body.style.color = "white"

 

 

Navigator Object Method and Property

Used when interacting with the browser's capabilities related to the client at runtime. The navigator object contains information about the browser and the operating system, and it offers methods to perform tasks like detecting the user's location and managing the connection status.

 

Methods of the navigator Object:

  • geolocation: This attribute returns a Geolocation object that can be used to obtain the position of the device. It's not a method by itself but an object with its own methods.
    • getCurrentPosition(success, error, options): Calls the success callback with the current position as soon as it's available. Optional error callback can be provided for handling any errors, and options can modify the behavior of the location retrieval.
    • watchPosition(success, error, options): Similar to getCurrentPosition but calls the success callback every time the location changes.
    • clearWatch(id): Stops watching the position by clearing the watch set up by watchPosition.

Console Object?

The console object provides access to the browser's debugging console. It is part of the Web APIs provided by browsers and is primarily used for debugging purposes. The console offers a variety of functions that developers can use to log information, errors, warnings, and more, helping them to debug and test their web applications directly within the browser.

  • console.error() : Outputs an error message to the console. This typically displays the message with a red icon and text, making it easily distinguishable in the console output.
  • console.log() :  Logs general information to the console. It's the most frequently used method to display simple messages or variables' values during development.

 

 

 

 

 

HTTP Request : AJAX CODE 

document.getElementById('submitButton').addEventListener('click', function() {
    var userData = document.getElementById('inputData').value; // Get the user input
    fetch('/processInput', {
            method: 'POST',
            headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ data: userData }) // Send the data as JSON
    })
    .then(response => response.json()) // Parse the JSON response
    .then(data => {
            document.getElementById('responseArea').innerText = data.message; // Display the response
    })
    .catch(error => console.error('Error:', error));
});

 

Fetch API

  • fetch : The fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It returns a Promise that resolves to the Response to that request, whether it is successful or not.
    • Fetch Function: This function initiates an HTTP request to the server at the endpoint /processInput.
      • Method, Headers, and Body: The method specifies what type of HTTP method to use (e.g., POST, GET). The headers provide additional information needed for the request like content type. The body includes the data sent to the server, formatted as a JSON string.
      • Handling Responses: The .then() and .catch() methods handle the response and errors, respectively. They ensure that once the server processes the request and sends back a response, it's appropriately managed in your JavaScript application.
        • if the response is html text, ".then(response => response.text())" 을 통해서 body를 parsing해서 html로만들고,  
        • ".then(html => { document.getElementById('location').innerHTML = html;" innerhtml이라는 attribute을 통해서 html 중에서 contents를 바꾸고자하는 html을 부분적으로 업데이트 할 수 있다는 것.
      • response has got json method that parse the response's body into json data type.
  • Json Object
    • JSON is treated as a global object that provides methods for parsing JSON content into JavaScript objects and converting JavaScript objects into JSON format.
    • Method
      • JSON.parse(): Converts a JSON string into a JavaScript object JSON.x`
      • JSON.stringify(): Converts a JavaScript JSON object into a JSON string
        • Serialization: This process converts the JavaScript object into a string that can be transmitted over a network or stored in a file or database. & Formatting : check if the json are well formatted
      • json.key = value : JSON Object of javascript are made easy to parse value of key using its attribute.

 

 

'개발기술 > 프론트엔드' 카테고리의 다른 글

백엔드 개발자와 프론트 엔드 이해도  (0) 2025.02.12
Java, Javascript, Python 비교  (1) 2025.01.14
DOM  (0) 2025.01.09
톰캣 설치를 통한 JSP 사용법  (0) 2024.07.01
HTML, CSS  (0) 2024.06.09