JavaScript编码字段不会破坏显示 [英] JavaScript encode field without spoiling the display
问题描述
我想在提交$ _GET请求之前编码一个特定的搜索字段。我正在做的是在提交表单之前在这个字段上应用encodeURIComponent()函数
$('#frmMainSearch') .submit(function(){
var field = $(this).find('#searchinput');
field.val(encodeURIComponent(field.val()));
} );
问题在于,只要文本被编码,该字段就会显示编码文本,有点奇怪。有什么我可以做的,以避免它?
例如:
I type Hello&你好即可。当我点击提交按钮时,它会在页面刷新之前变成类似 Hello%26 Hello> 的内容。我想避免这种情况。
任何解决方案?
谢谢
我最近不得不解决这个问题。以下是我的工作方式:
-
创建您想要面向用户的输入字段,例如: p>
< input class =真的好看的字段
id =search-text-display
placeholder =搜索东西...
type =text>
-
注意,在显示的字段中,
code>属性被特别省略。这将使
字段不在提交的表单中,因此您没有未使用的参数。search-text-display -
创建一个隐藏字段,这就是实际 将用于提交的内容,如下所示:
< input id =search-textname =search_texttype =hidden>
-
在表单提交前从表单中捕获提交事件以填充隐藏字段,像这样:
$('#site-search')。submit(function(){
$(' ($('#search-text-display').val())
);
}); val(
encodeURIComponent($('#search-text-display')。
这会将输入字段显示给您
参数:{utf8=>✓, search_text=>hello%20%26%20hello}
I want to encode a specific search field before submitting as a $_GET request. What I am doing is to apply encodeURIComponent() function over that field before the form is submitted
$('#frmMainSearch').submit(function() {
var field = $(this).find('#searchinput');
field.val(encodeURIComponent(field.val()));
});
the issue is that as soon as the text is encoded, the field displays the encoded text which looks a bit weird. Is there anything I can do to avoid it?
Example: I type Hello & Hello. When I click submit button it turns into something like Hello %26 Hello before the page is refreshed. I want to avoid that.
Any solution?
Thanks
I recently had to solve this same problem. Here's how I did it:
Create the input field that you want to be user-facing, such as this:
<input class="really-nice-looking-field" id="search-text-display" placeholder="Search for stuff..." type="text">
Notice that with the field that's displayed, the
name
attribute is specifically omitted. This will keep thesearch-text-display
field out of the submitted form, so you don't have unused parameters coming through.Create a hidden field, which is what will actually be used for the submit, like so:
<input id="search-text" name="search_text" type="hidden">
Capture the submit event from your form to populate the hidden field before the form is submitted, like so:
$('#site-search').submit(function() { $('#search-text').val( encodeURIComponent($('#search-text-display').val()) ); });
This will leave the input field displayed to your users untouched while your parameters come through escaped, as needed:
Parameters: {"utf8"=>"✓", "search_text"=>"hello%20%26%20hello"}
这篇关于JavaScript编码字段不会破坏显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!