使用jQuery通过url传递值的更好方法

时间:2015-01-13 22:48:33

标签: jquery forms variables url

我正在使用表单插件的Wordpress网站上工作。该插件使用一种不寻常的方法发布表单值,似乎不支持传递任何$ POST或$ GET变量的方法。即$ POST上的print_r返回一个空数组。奇怪的是,该插件还“需要”表单的操作为空白。基本上它所做的只是在提交数据后将您重定向到“谢谢页面”。

我需要在后续表单中预先填充一个单一字段,因此我想到了使用javascript将所需变量传递给“感谢页面”网址,这真正导致了后续表单。通常这个url应该被硬编码为表单中的隐藏字段,但我决定只是动态创建它。因为遗憾的是我比js更熟悉jQuery,所以我决定使用它。

所以无论如何我使用下面的代码让它工作,但感觉有更好的方法,并担心可能会对我这样做的方式产生一些不可预见的后果。

$('#address').keyup(function () {
   string = this.value; //store value from address input field
   string = string.replace(/\s/g,"%20"); // Replace spaces 
   var url = "http://example.com/?page_id=156"; // url to thank you page 
   jQuery('#thankyou').html('<input type="hidden" name="thank_you_page" value="' + url  + '&property=' + string + '" type="text">');  // add the required hidden field to the form
 });

1 个答案:

答案 0 :(得分:2)

而不是使用jQuery注入。您可以简化并将隐藏的直线添加到带有ID的表单中。

例如

<form>
  <input id="thank_you_page_field" type="hidden" name="thank_you_page" value="" type="text">
</form>

然后只使用jquery填充它。

例如

$('#address').keyup(function () {
   string = this.value; //store value from address input field
   string = string.replace(/\s/g,"%20"); // Replace spaces 
   var url = "http://example.com/?page_id=156"; // url to thank you page 
   url += '&property=' + string
   jQuery('#thank_you_page_field').val(url) // update the value.
 });

也代替

 string = string.replace(/\s/g,"%20"); // Replace spaces 

尝试encodeURIComponent() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

最终代码可能看起来像这样

$('#address').keyup(function () {
   var url = "http://example.com/?page_id=156"; // url to thank you page 
   url += '&property=' + this.value //append the value
   $('#thank_you_page_field').val(encodeURIComponent(url)) // update the value
 });
相关问题