Câu hỏi phỏng vấn Javascript
Câu hỏi

Explain how JSONP works (an...

Câu trả lời

JSONP, which stands for "JSON with Padding," is a technique used to overcome the limitations imposed by the same-origin policy in web browsers, allowing data to be fetched from a server located on a different domain than the one the web page is hosted on. This is different from AJAX, which typically uses the XMLHttpRequest object for asynchronous data fetching within the same domain.

How JSONP Works

  1. Client Request: The process begins when the client (usually a web browser) needs to fetch data from a different domain. Instead of using XMLHttpRequest, the client dynamically creates a <script> tag in the HTML document. The src attribute of this script tag is set to the URL of the data request, which includes a special query parameter for a callback function[1][4][6][10].

  2. Server Response: The server, upon receiving the request, processes it and returns the data not in plain JSON format, but wrapped inside a function call. The function name is the one specified by the callback parameter in the request URL. For example, if the callback parameter was callbackFunc, the server might respond with callbackFunc({"key": "value"})[1][4][6][10].

  3. Execution and Data Handling: When the script is loaded, the browser executes the function call embedded in the response. This function call passes the JSON data as an argument to the callback function predefined in the client’s environment. The client-side JavaScript can then use this data as needed[1][4][6][10].

How JSONP is Not Really AJAX

  • Different Mechanism: Unlike AJAX, JSONP does not use the XMLHttpRequest object. Instead, it works by dynamically inserting a <script> tag into the HTML document. This fundamental difference means that JSONP is not bound by the same-origin policy restrictions that apply to AJAX requests[1][4][6][10].

  • Limited to GET Requests: JSONP can only perform GET requests because it involves fetching a ...

senior

senior

Gợi ý câu hỏi phỏng vấn

senior

Explain the Prototype Design Pattern

senior

What are the actual uses of ES6 WeakMap?

middle

What are the differences between ES6 class and ES5 function constructors?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào