将javascript变量传递给嵌入式调查表单

时间:2016-10-16 14:28:14

标签: javascript urlvariables

我经常环顾四周,但似乎无法找到解决这个问题的最佳方法。如何将变量值(p1,p2,p3)输入到此代码底部的URL中?

我将使用" +"'格式化的变量作为空格,将它们格式化为"%20"作为空间;然后,将它们传递到用于此嵌入式字体的此代码底部的链接中。

<script type="text/javascript">// <![CDATA[
function getParameterByName (name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
  results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var p1 = getParameterByName('p1')
var p2 = getParameterByName('p2')
var p3 = getParameterByName('p3')

p1 = p1.replace(/\+/g, "%20");
p2 = p2.replace(/\+/g, "%20");
p3 = p3.replace(/\+/g, "%20");
// ]]></script><script type="text/javascript">// <![CDATA[

function getParameterByName (name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
  results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var p1 = getParameterByName('p1')
var p2 = getParameterByName('p2')
var p3 = getParameterByName('p3')

p1 = p1.replace(/\+/g, "%20");
p2 = p2.replace(/\+/g, "%20");
p3 = p3.replace(/\+/g, "%20");
// ]]></script>

<!-- Change the width and height values to suit you best -->
<div class="typeform-widget" 
     data-url="https://eatforklore.typeform.com/to/XPDPsx?p1=xxxxx&amp;p2=xxxxx&amp;p3=xxxxx&amp;p4=xxxxx" 
     data-text="Mo. 1 Product Reviews" 
     style="width:100%;height:500px;">
</div>
<script>
(function(){var qs,js,q,s,d=document,gi=d.getElementById,ce=d.createElement,gt=d.getElementsByTagName,id='typef_orm',b='https://s3-eu-west-1.amazonaws.com/share.typeform.com/';if(!gi.call(d,id)){js=ce.call(d,'script');js.id=id;js.src=b+'widget.js';q=gt.call(d,'script')[0];q.parentNode.insertBefore(js,q)}})()
</script>

1 个答案:

答案 0 :(得分:0)

您的getParameterByName函数需要两个参数,但只有一个参数。您应该使用data-url传递div的{​​{1}}属性。

.dataset.url
function getParameterByName(name, url) {
   if (!url) url = window.location.href;
   name = name.replace(/[\[\]]/g, "\\$&");
   var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
   results = regex.exec(url);
   if (!results) return null;
   if (!results[2]) return '';
   console.log('The value of ' + name + ' is: ' + results[2].replace(/\+/g, " "));
   return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var p1 = getParameterByName('p1', document.getElementsByClassName('typeform-widget')[0].dataset.url)
var p2 = getParameterByName('p2',document.getElementsByClassName('typeform-widget')[0].dataset.url)
var p3 = getParameterByName('p3', document.getElementsByClassName('typeform-widget')[0].dataset.url)

p1 = p1.replace(/\+/g, "%20");
p2 = p2.replace(/\+/g, "%20");
p3 = p3.replace(/\+/g, "%20");