首頁  >  文章  >  web前端  >  JS的表單傳值與URL編碼轉換詳解

JS的表單傳值與URL編碼轉換詳解

php中世界最好的语言
php中世界最好的语言原創
2018-03-27 16:38:171858瀏覽

這次帶給大家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>

執行後:



#我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

JS的圖片處理與合成詳解

Vue.directive( )的圖文詳解

#

以上是JS的表單傳值與URL編碼轉換詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn