首页 > 解决方案 > 如何在 Javascript 中传递 url 中的字符串?

问题描述

我正在尝试制作一个从私有 JSON dns 服务器访问 iframe 内不同站点的应用程序。我已经完成了主要代码,但现在我正在尝试使其能够通过 url 访问。(Ex. https://thissite.info?url='test.json'&dnsserver='https://thissite.info') 如果变量未在 url 中定义,我还希望它默认为一个值。为此,我使用以下代码:

  function setup(){
  var dns = document.getElementById("dns");
  var urlbar = document.getElementById("urlbar");
  var frame = document.getElementById("viewport");
  if (typeof url === "undefined") {
    url = 'Welcome Page URL Here';
  } else {
    urlbar.value = url;
  }
    if (typeof dnsserver === "undefined") {
    dnsserver = 'Default Server Here';
  } else {
    dns.value = dnsserver;
  }
  var xmlhttp = new XMLHttpRequest();
       xmlhttp.onreadystatechange = function() {
         console.log(this.status)
         if(this.readyState == 4 && this.status == 200){
           var response = JSON.parse(this.responseText);
           frame.src=response;
           console.log("Request Completed with 200");
       };
         if(this.readyState == 4 && this.status == 404){
           console.log("Website Not Found");
           frame.src='404.html'
       };
       }
      xmlhttp.open("GET",dnsserver + url + '.json', true);
      xmlhttp.send();
      console.log("Request Sent");
}

但即使我在 URL 中传递变量,它也不接受它。

标签: javascriptjsonhttps

解决方案


<script type="text/javascript"> $(function () { $("#btnQueryString").bind("click", function () { var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val()); window.location.href = url; }); }); </script> <input type="button" id="btnQueryString

推荐阅读