Home > Web Front-end > JS Tutorial > body text

How to use JS to implement POST across domains

php中世界最好的语言
Release: 2018-05-23 13:40:33
Original
1508 people have browsed it

This time I will show you how to use JS to implement POST across domains. What are the precautions for implementing POST across domains with JS? . 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:

How to find the least common multiple and greatest common divisor in JS

Using the region selector component in VUE Detailed explanation

The above is the detailed content of How to use JS to implement POST across domains. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template