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:
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
}
Next, create a
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo';
Once the
document.getElementsByTagName('head')[0].appendChild(script);
For modern browsers, you can simplify this line to:
document.head.appendChild(script);
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);
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