Javascript 转义通过 POST 发送的 jQuery 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2231810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:22:11  来源:igfitidea点击:

Escaping jQuery data being sent via POST

javascriptjqueryescaping

提问by Matt

I'm using jQuery.ajax to extract form data from a page, and send it to my database (via another PHP page).

我正在使用 jQuery.ajax 从页面中提取表单数据,并将其发送到我的数据库(通过另一个 PHP 页面)。

The form information is collected by:

表单信息由以下人员收集:

var X=$('#div1').val();
var Y=$('#div2').val();

This is used to build the POST string, i.e.

这用于构建POST字符串,即

var data='varx='+X+'&vary='+Y;

Obviously this is problematic if an ampersand character is used. What is the best method to escape the variables, particularly so that the user can safely use an ampersand (&) ?

显然,如果使用与号字符,这是有问题的。转义变量的最佳方法是什么,特别是为了让用户可以安全地使用与号 (&) ?

Thanks!

谢谢!

回答by LiraNuna

encodeURIComponentwill do what you are looking for.

encodeURIComponent会做你正在寻找的。

var X = encodeURIComponent($('#div1').val());
var Y = encodeURIComponent($('#div2').val());

This will encode all potentially insecure characters.

这将对所有可能不安全的字符进行编码。

回答by Alex

The best would be using an object for the data.

最好的方法是为数据使用一个对象。

jQuery.post("yourScript.php", {
   varx: X,
   vary: Y
});

or

或者

jQuery.ajax({
      url: "yourScript.php",         
      type: "POST",
      data: ({varx: X, vary: Y}),
      dataType: "text",
      success: function(msg){
         alert(msg);
      }
   }
);

You can also use jQuery's serialize() to get your form data as a serialized querystring:

您还可以使用 jQuery 的 serialize() 将表单数据作为序列化查询字符串获取:

var data = jQuery(formSelector).serialize();

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types.

.serialize() 方法以标准 URL 编码表示法创建文本字符串。它对表示一组表单元素的 jQuery 对象进行操作。表单元素可以是多种类型。

Way prettier in my opinion :-)

在我看来更漂亮:-)

回答by Dmitris

You can use escape function of JavaScript

您可以使用 JavaScript 的转义函数

var data='varx='+escape(X)+'&vary='+escape(Y);