This time I will bring you a detailed explanation of the steps of the JS cross-domain POST method. What are the precautions for the JS cross-domain POST method? The following is a practical case, let's take a look.
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(); }
<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>
<!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="'+k+'" value="'+data[k]+'" />' } template = template + ' <input type="text" name="jsoncallback" value="function callback(data) { parent.postMessage(data, \'*\'); } callback" />' + '</form>' + '<'+'script>' + 'document.getElementById("form1").submit();' + '</'+'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>
window.onmessage = function(e) { //可通过 e 来判断来源,并做一些安全方面的处理,此处读者自己去研究吧,可以加个 console.log(e) 看看 e 有哪些内容。 if (callback) callback(e.data); }
How to use Vue to implement tree view data
What are the methods for JS to implement DOM tree traversal?
The above is the detailed content of Detailed explanation of the steps to implement POST across domains using JS. For more information, please follow other related articles on the PHP Chinese website!