通过POST发送jQuery数据 [英] Escaping jQuery data being sent via POST

查看:84
本文介绍了通过POST发送jQuery数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

表单信息是收集者:

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

这是用来构建POST字符串,即

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

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 (&) ?

谢谢!

推荐答案

最好的是使用数据的对象。

The best would be using an object for the data.

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

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

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

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

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




.serialize()方法创建一个文本
string在标准的URL编码的
表示法。它运行在一个jQuery
对象上,表示一组
元素。表单元素可以是
几种类型。

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.

在我看来,方式更漂亮: - )

Way prettier in my opinion :-)

这篇关于通过POST发送jQuery数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆