如何发送操作员"&"通过Ajax查询?

时间:2017-08-17 03:53:04

标签: javascript php jquery mysql ajax

我目前正在使用以下ajax函数来发送ajax查询。

$.ajax({
    type: "POST",
    url: "insert.php",
    data: dataString,
    cache: false,
    success: function (htmltwo) {},
    error: function (htmltwo) {}
});

问题是当我发送包含操作符"&"的文本时,删除了操作员右侧的项目。以下是我的dataString。

var dataString = 'id=' + id + '&dateoccur=' + dateoccur + '&timeoc=' + 
timeoc + '&hitype=' + hitype + '&hid=' + hid;

因此,例如,如果hid是包含" EEEE& LLLLL"的文本,则&和/或将在服务器端接收时删除。因此,在服务器端,将收到" EEEE"。我假设ajax认识到这一点,因为它是dataString变量的一部分。我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以在Javascript中使用encodeURIComponent&等字符进行编码,然后在服务器上对其进行解码。

var hidValue = "EEEE&LLLLL";

var hidValueEncoded = encodeURIComponent(hidValue);
console.log(hidValueEncoded);

答案 1 :(得分:0)

我总是建议使用对象而不是字符串。然后jQuery会自动编码所有内容。

var dataString = {
    id: id,
    dateoccur: dateoccur,
    timeoc: timeoc,
    hitype: hitype,
    hid: hid
};

它更具可读性,恕我直言。

但如果您真的想自己构建字符串,请使用encodeURIComponent,如Nisarg Shah的答案。您应该对所有参数执行此操作,除非您确定它们不包含任何特殊字符。