본문 바로가기

개발기술/Web Dev

프론트엔드 자바스크립트 & http request

<JavaScript>

JavaScript

문서의 내용와 구조를 잡아주는 HTML은 한번 출력된 문서는 내용이 바뀌지 않는 정적인 언어이기에, JavaScript는 문서를 동적으로 바꿔 사용자와 상호작용하기 위해 도입된 언어이다. 

 

callback functions : These functions are expected to accept parameters that are predefined by the context in which

they are used. if A function use B function as callback, B function's parmeter is defined by A function.  A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. In JavaScript, callbacks are a way to ensure certain code doesn't execute until other code has already finished execution. the extensive use of callbacks in JavaScript is due to particularly its asynchronous nature and event-driven programming model.

 

Why Asynchronous? : In the context of web browsers, there are many tasks like loading images, downloading files, or fetching data from a server. These tasks can take time to complete and you wouldn't want your browser to freeze or stop responding while these tasks are being done. is unique and designed to work within the constraints of a single-threaded execution mode (Synchronous : Can be less fluid, as it involves a full page reload Asynchronous : Provides a smoother experience by updating parts of the web page without a reload)

 

 

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

JavaScript Keyword

In Operator(javascript property in object) : The in operator returns true if the specified property is found in the specified object or its prototype chain. Its syntax is:

 

 

 

 

JavaScript Method

 

alert("TexttoDisplay") : 경고창을 메세지와 함께 출력한다.  ex) <input type="button" onclick="alert("hello")>

.innerHTML : it allows you to replace the existing HTML content within a given element with new content, which can include plain text as well as HTML tags.

.textContent : updating only the text of an element

 

String Object Method

Stringinstance.toUpperCase() : 문자열을 대문자로 변환 후 반환함

Stringinstance.length() : 문자열의 길이를 반환함

Stringinstance.IndexOf() : 문자의 index를 찾아서 반환하며, 찾지 못하면 -1를 반환함.

Stringinstance.trim() : whitespace를 제거함

 

 

 

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.

 

 

Promise Object

  • A Promise is an object representing the eventual completion or failure of an asynchronous operation and its value. Essentially, it's a placeholder for the consequences.. then() and catch() are part of the broader implementation of Promises in JavaScript. 
  • then Method
    • promise.then(onFulfilled, onRejected)
      • onFulfilled — A function to be called if the promise is fulfilled.  tak fulfillment value as argument.
      • onRejected — A function to be called if the promise is rejected. This is optional.
      • Returns: then returns a new promise, which can be chained with additional then or catch methods.
    • The catch method is used to register a callback for handling any errors.

 

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.