5 solutions to js cross-domain requests_javascript skills
The solutions for cross-domain request data mainly include the following solutions:
JSONP方式 表单POST方式 服务器代理 Html5的XDomainRequest Flash request
Separate instructions:
1. JSONP:
Intuitive understanding:
It is to dynamically register a function on the client
function a(data), and then pass the function name to the server, and the server returns an a({/*json*/}) to the client to run, thus calling the client's
function a(data), thus achieving cross-domain.
Birth background:
1. Ajax directly requests ordinary files, which has the problem of cross-domain access without permission. Regardless of whether it is a static page, dynamic web page, web service, or wcf, as long as it is a cross-domain request, it will not work.
2. However, when calling js files on the web page, it is not affected by this
3. Further promotion, we found that all tags with Src attributes have cross-domain capabilities, such as: <script><img src="/static/imghwm/default1.png" data-src="http://remoteserver.com/remote.js" class="lazy" alt="5 solutions to js cross-domain requests_javascript skills" ><iframe></script>
4. Therefore, if you currently want to access data cross-domain through the pure web side (ActiveX controls, server-side proxies, Websockets belonging to the future HTML5, etc. are not included), you can only use the following method: on the remote server Try to load the data into text in js format for client calling and further processing.
5. JSON is a pure character data format and can be natively supported by js.
6. Here is the solution: the web client calls the dynamically generated js format file (usually with json as the suffix) on the cross-domain server in exactly the same way as calling the script.
7. After the client successfully calls the json file, it will get the required data, and the rest is to process it according to its own needs.
8 In order to facilitate the client to use data, an informal transmission protocol has gradually formed, called jsonp. A key point of this protocol is to allow users to pass a callback parameter to the server, and then when the server returns data, it will use this callback parameter as a function name to wrap the json data, so that the client can customize its own function to process the returned data.
Detailed implementation:
Whether it is jQuery, extjs, or other frameworks that support jsonp, the work they do behind the scenes is the same. Let me explain the implementation of jsonp on the client step by step:
1. We know that even if the code in the cross-domain js file (which of course complies with the web script security policy), the web page can be executed unconditionally.
There is a remote.js file code in the root directory of remote server remoteserver.com as follows:
alert('I am a remote file');
The local server localserver.com has a jsonp.html page code as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"></script> </head> <body> </body> </html>
There is no doubt that a prompt window will pop up on the page, showing that the cross-domain call is successful.
2. Now we define a function on the jsonp.html page, and then call it by passing in data in remote.js.
jsonp.html page code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> var localHandler = function(data){ alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result); }; </script> <script type="text/javascript" src="http://remoteserver.com/remote.js"></script> </head> <body> </body> </html>
The remote.js file code is as follows:
localHandler({"result":"I am the data brought by remote js"});
Check the results after running. The page successfully pops up a prompt window, showing that the local function was successfully called by the cross-domain remote js, and the data brought by the remote js was also received. I am very happy that the purpose of cross-domain remote data acquisition has been basically achieved, but another question arises. How do I let the remote js know the name of the local function it should call? After all, jsonp servers have to face many service objects, and the local functions of these service objects are different? Let's look down.
3. Smart developers can easily think that as long as the js script provided by the server is dynamically generated, the caller can pass a parameter to tell the server "I want a js code that calls the XXX function , please return it to me", so the server can generate js scripts and respond according to the client's needs.
Look at the code of the jsonp.html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> // 得到航班信息查询结果后的回调函数 var flightHandler = function(data){ alert('你查询的航班结果是:票价 ' + data.price + ' 元,' + '余票 ' + data.tickets + ' 张。'); }; // 提供jsonp服务的url地址(不管是什么类型的地址,最终生成的返回值都是一段javascript代码) var url = "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998&callback=flightHandler"; // 创建script标签,设置其属性 var script = document.createElement('script'); script.setAttribute('src', url); // 把script标签加入head,此时调用开始 document.getElementsByTagName('head')[0].appendChild(script); </script> </head> <body> </body> </html>
This time the code has changed a lot. It no longer directly writes the remote js file, but codes to implement dynamic query. This is also the core part of the jsonp client implementation. The focus in this example is how to Complete the entire process of jsonp calling.
We see that a code parameter is passed in the calling URL, telling the server that what I want to check is the information of flight CA1998, and the callback parameter tells the server that my local callback function is called flightHandler, so please pass the query results Call this function.
flightHandler({ "code": "CA1998", "price": 1780, "tickets": 5 });
我们看到,传递给flightHandler函数的是一个json,它描述了航班的基本信息。运行一下页面,成功弹出提示窗口,jsonp的执行全过程顺利完成!
4、到这里为止的话,相信你已经能够理解jsonp的客户端实现原理了吧?剩下的就是如何把代码封装一下,以便于与用户界面交互,从而实现多次和重复调用。
什么?你用的是jQuery,想知道jQuery如何实现jsonp调用?好吧,那我就好人做到底,再给你一段jQuery使用jsonp的代码(我们依然沿用上面那个航班信息查询的例子,假定返回jsonp结果不变):
OK,服务器很聪明,这个叫做flightResult.aspx的页面生成了一段这样的代码提供给jsonp.html(服务端的实现这里就不演示了,与你选用的语言无关,说到底就是拼接字符串):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <script type="text/javascript" src=jquery.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type: "get", async: false, url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998", dataType: "jsonp", jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据 success: function(json){ alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。'); }, error: function(){ alert('fail'); } }); }); </script> </head> <body> </body> </html>
是不是有点奇怪?为什么我这次没有写flightHandler这个函数呢?而且竟然也运行成功了!哈哈,这就是jQuery的功劳了,jquery在处理jsonp类型的ajax时(还是忍不住吐槽,虽然jquery也把jsonp归入了ajax,但其实它们真的不是一回事儿),自动帮你生成回调函数并把数据取出来供success属性方法来调用,是不是很爽呀?
以上所述就是本文的全部内容了,希望大家能够喜欢。

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version
