簡體   English   中英

檢索輸入表單中的特殊字符

[英]retrieve special characters in an input form

我有一個 HTML 表單,其中包含不同的輸入字段(其中大部分是文本值),但是一旦填充了額外的字符(例如 %),我就無法檢索它。

這是 HTML 表單:

<form id="myform" class="form-horizontal" action="javascript:notif()" >
  <fieldset>
    <div class="control-group">
      <label class="control-label" for="focusedInput">nom</label>
      <div class="controls">
        <input name="nom" class="input-xlarge focused" id="focusedInput" type="text" value="">
      </div>
    </div>

    <div class="control-group">
      <label class="control-label" for="date01">Date</label>
      <div class="controls">
        <input type="text" name="date" class="input-xlarge datepicker" id="date" value="">
      </div>
    </div>

    <div class="control-group">
      <label class="control-label" for="focusedInput">Titre</label>
      <div class="controls">
        <input name="page" class="input-xlarge focused" id="focusedInput" type="text" value="">
       </div>
    </div>  
...

以及用於檢索字段的 Javascript:

var s_data = $('#myform').serializeArray();
            $.get("webAdd?nom="+s_data[0].value+"&date="+s_data[1].value+"&titre="+s_data[2].value+"&message="+s_data[3].value+"&page="+s_data[4].value+"&commentaires="+s_data[5].value,function(response) {});

我的問題很簡單,但我無法解決它:只要任何 s_data[x] 字段包含諸如“25% 折扣”之類的文本,檢索到的文本字段為空。

我知道 % 字符用於其他目的,但如何檢索帶有任何特殊字符的字段?

由於您請求的是網址,因此您需要對用戶輸入進行編碼。 否則 url 將被錯誤解析。 為此,將每個s_data[0].value包裝在encodeURIComponent就像這樣encodeURIComponent(s_data[0].value) 這將編碼特殊字符,因此它們可以成為 url 的一部分而不會破壞它。

$.get("webAdd?nom="+encodeURIComponent(s_data[0].value)+"&date="+encodeURIComponent(s_data[1].value)+"&titre="+encodeURIComponent(s_data[2].value)+"&message="+encodeURIComponent(s_data[3].value)+"&page="+encodeURIComponent(s_data[4].value)+"&commentaires="+encodeURIComponent(s_data[5].value),function(response) {});

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

您必須對傳遞給 jQuery 的查詢字符串進行編碼,但是當您的表單輸入具有您在查詢字符串中使用的名稱時,如果您讓 jQuery 為您完成工作,這應該是直接的

$.get("webAdd", $('#myform').serialize()).then(function(response) {

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM