JS的表单传值与URL编码转换详解

H5教程评论1K views阅读模式

这次给大家带来JS的表单传值与URL编码转换详解,JS表单传值与URL编码转换详解的注意事项有哪些,下面就是实战案例,一起来看一下。

注意:

这里写了两个网页

因为URL传过去的数据不支持中文字符和一些特殊符号 所以需要转换一下编码

实现效果:网页1的表单数据传到网页2并显示出来

网页1代码如下:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
  <title>document</title> 
</head> 
<body> 
  <!--test_form.html为需要发送数据到的网页,https://idaobin.com/test/test_form.html --> 
  <!--表单数据将通过method属性附加到 URL上--> 
  <!--submit表单提交到另一个网页--> 
  <form action="test_form.html" method="GET" target="_blank"> 
    账号:<input type="text" name="code"><br> 
    姓名:<input type="text" name="str"><br> 
    <input type="submit"> 
  </form> 
</body> 
</html>

网页2代码如下:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
  <title>document</title> 
  <script type="text/javascript" src="jquery-3.2.1.js"></script> 
  <!--URL编码转换,只对第二个输入框转换--> 
  <script> 
    window.onload=function(){ 
      var a=document.getElementById("str").innerText; 
      var b=(decodeURIComponent(a)); 
      document.getElementById("str").innerText=b; 
    } 
    // 以下是jquery代码 
    // $(function(){ 
    //   var c=$("#str").text(); 
    //   var d=(decodeURIComponent(c)); 
    //   $("#str").text(d); 
    // }); 
  </script> 
</head> 
<body> 
  <p>提交过来的数据页面</p> 
  账号:<span id="code"></span><br> 
  姓名:<span id="str"></span> 
</body> 
<!--获取表单传过来的数据--> 
<script> 
  function UrlSearch(){ 
    var name,value; 
    var str=location.href; 
    var num=str.indexOf("?"); 
    str=str.substr(num+1); 
    var arr=str.split("&"); 
    for(var i=0;i<arr.length;i++){ 
      num=arr[i].indexOf("="); 
      if(num>0){ 
        name=arr[i].substring(0,num); 
        value=arr[i].substr(num+1); 
        this[name]=value; 
      } 
    } 
  } 
  var Request=new UrlSearch(); 
  document.getElementById("code").innerHTML=Request.code; 
  document.getElementById("str").innerHTML=Request.str; 
</script> 
</html>

运行后:

JS的表单传值与URL编码转换详解

相信看了本文案例你已经掌握了方法,更多精彩请关注H5教程其它相关文章!

推荐阅读:

JS的图片处理与合成详解

Vue.directive()的图文详解

以上就是JS的表单传值与URL编码转换详解的详细内容,更多请关注H5教程其它相关文章!

企鹅博客
  • 本文由 发表于 2019年10月3日 01:31:28
  • 转载请务必保留本文链接:https://www.qieseo.com/352852.html

发表评论