2

Hoo boy. A weird one I guess!

getting input from a form, I want to make sure there are no western characters, punctuation or numbers before sending it to a php script for creating some xml...

from form name = "a"

$('form').submit(function() {

text = ($(this).serialize());

text = text.substr(2,text.length)

text = text.replace(/[^\u3040-\u30FF^\uFF00-\uFFEF^\u4E00-\u9FAF^\u3400-\u4DBF]/g,'');

---> text goes to php script using .ajax

However, the Japanese is being converted to ASCII before it gets to the regex!

eg. あああ becomes %E3%81%82%E3%81%82%E3%81%82

Any suggestions?

4

1 回答 1

1

我会在序列化之前交换它并更改输入,如下所示:

$('form').submit(function() {
  $(this).find(':text, textarea').val(function(i, v) {
    return v.replace(/[^\u3040-\u30FF^\uFF00-\uFFEF^\u4E00-\u9FAF^\u3400-\u4DBF]/g,'');
  });
  var text = ($(this).serialize());
  //submit form....
});

这用于.val()在序列化之前根据正则表达式获取和替换旧值(更重要的是,encodeURIComponent()在那里被调用)。


另一种选择是在.serialize()步骤中间自己执行正则表达式,如下所示:

$('form').submit(function() {
  var arr = $(this).serialzeArray();
  $.each(arr, function() {
    this.value = this.value.replace(/[^\u3040-\u30FF^\uFF00-\uFFEF^\u4E00-\u9FAF^\u3400-\u4DBF]/g,'');
  });
  var postData = $.param(arr);
});

.serialize()真的就是$.param($(this).serializeArray())这样,我们所做的就是在这里拆分它,获取数组中创建并在每个对象上运行正则表达式value的对象对。之后,我们将更改后的数组(无西方字符)传递给序列化为字符串。{name:'name',value:'value'}.serializeArray()$.param()

于 2010-08-20T11:48:51.053 回答