Home Web Front-end JS Tutorial Detailed explanation of JS cross-domain POST implementation steps

Detailed explanation of JS cross-domain POST implementation steps

May 12, 2018 am 11:18 AM
javascript post Detailed explanation

This time I will bring you a detailed explanation of the steps to implement JS cross-domain POST. What are the precautions for JS cross-domain POST implementation? Here are practical cases, let’s take a look.

javascript Cross-domain is a very common problem, among which jsonp is the most commonly used method, but jsonp only supports get, not post, so if you want to post some data through jsonp , the head is big.

Post is implemented by generating a form in an iframe, and returns the value to the caller through postMessage.

In the first step, we first implement a back-end code that accepts jsonp. As for what language to use for implementation, you decide for yourself.

c#The code is:

protected void Page_Load(object sender, EventArgs e)
    {
      StringBuilder sbRet = new StringBuilder();
      sbRet.Append("<script>");
      sbRet.Append(Request["jsoncallback"]);
      sbRet.Append("({");
      foreach (string k in Request.Form) {
        if (k == "jsoncallback") continue;
        sbRet.Append("'"+k+"':'"+Request.Form[k]+"'");
      }
      
      sbRet.Append("});");
      sbRet.Append("</script>");
      Response.Write(sbRet.ToString());
      Response.End();
    }
Copy after login

For example, what you want to return to me is { userName:'user1', password:'pass1' } , when I call http://localhost/test When ?jsoncallback=callme

you actually return<script>callme({ userName:'user1', password:'pass1' })</script>.

The second step is to build a post test page in the local folder, such as d:\test.html

<form action="http://localhost/test" method="post">
  <input type="text" name="userName" value="user1" />
  <input type="text" name="password" value="pass1" />
  <input type="text" name="jsoncallback" value="callme" />
  <input type="submit" value="提交" />
</form>
Copy after login

The third step is to browse and click submit to see if the returned value is < ;script>callme({ userName:'user1', password:'pass1' }) means there is no problem with the back-end program.

The fourth step, we write a general code to implement the above html.

<!doctype html>
<html>
  <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>测试一哈</title>
  </head>  
  <body>   
  <script>
  //源码 开始
   function postJSONP(url, data, callback) {
    var template = '<form action="{{url}}" method="post" id="form1">';   
    for (var k in data) {
     template = template
       + '  <input type="text" name="&#39;+k+&#39;" value="&#39;+data[k]+&#39;" />'
    }
      template = template 
      + '  <input type="text" name="jsoncallback" value="function callback(data) { parent.postMessage(data, \&#39;*\&#39;); } callback" />'
      + '</form>'
      + '<&#39;+&#39;script>'
      + 'document.getElementById("form1").submit();'
      + '</&#39;+&#39;script>';      
   template = template.replace("{{url}}", url);      
   var p = document.createElement("p");
   p.style.display = 'none';  
   p.innerHTML = '<iframe src=""></iframe>';
   document.body.appendChild(p);   
   var ifrm = p.children[0];
   var cwin = ifrm.contentWindow;
   cwin.document.write(template);   
   window.onmessage = function(e) {
   if (callback) callback(e.data);
   }
   }
   //源码 结束  
  //使用测试
   window.onload = function() {
   postJSONP('http://localhost:59898/WebForm1.aspx', { userName: '张静', password: '就不告诉你' }, function(data) {
    console.log(11, data);
   });
   postJSONP('http://localhost:59898/WebForm1.aspx', { 仓库: '1号大仓', 面积: '2万平米' }, function(data) {
    console.log(22, data);
   });
  }
 </script>
  </body>
</html>
Copy after login

The fifth step, security issues,

window.onmessage = function(e) {
  //可通过 e 来判断来源,并做一些安全方面的处理,此处读者自己去研究吧,可以加个 console.log(e) 看看 e 有哪些内容。
  if (callback) callback(e.data);
}
Copy after login

I believe you have read the case in this article After mastering the method, please pay attention to other related articles on the php Chinese website for more exciting content!

Recommended reading:

react-navigation usage summary (with code)

Common addition, deletion, modification and query operations of JS DOM elements Detailed explanation

The above is the detailed content of Detailed explanation of JS cross-domain POST implementation steps. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

How to implement PHP to jump to the page and carry POST data How to implement PHP to jump to the page and carry POST data Mar 22, 2024 am 10:42 AM

PHP is a programming language widely used in website development, and page jumps and carrying POST data are common requirements in website development. This article will introduce how to implement PHP page jump and carry POST data, including specific code examples. In PHP, page jumps are generally implemented through the header function. If you need to carry POST data during the jump process, you can do it through the following steps: First, create a page containing a form, where the user fills in the information and clicks the submit button. Acti in the form

Detailed analysis of C language learning route Detailed analysis of C language learning route Feb 18, 2024 am 10:38 AM

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

See all articles