"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Make Cross-Domain JSONP Requests in JavaScript Without External Libraries?

How to Make Cross-Domain JSONP Requests in JavaScript Without External Libraries?

Published on 2024-10-31
Browse:392

How to Make Cross-Domain JSONP Requests in JavaScript Without External Libraries?

Making JSONP Requests from JavaScript Without External Libraries

For cross-domain JSONP requests in JavaScript, external libraries like jQuery aren't always necessary. Here's a guide on achieving this using pure JavaScript:

Step 1: Create a Callback Function

Start by defining a callback function to receive and process the JSONP response. In the example provided, the foo function performs this task:

function foo(data) {
  // Do something with the JSON response here
}

Step 2: Dynamically Create a Script Element

Next, create a

var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo';

Step 3: Append the Script Element to the DOM

Once the

document.getElementsByTagName('head')[0].appendChild(script);

For modern browsers, you can simplify this line to:

document.head.appendChild(script);

Example

Bringing these steps together, here's a complete example of making a JSONP request in JavaScript without an external library:

function foo(data) {
  // Do stuff with JSON
}

var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'

document.head.appendChild(script);
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3