GET、PHP 中的 &

2022-01-04 00:00:00 get jquery php html ajax

我有一个简单的表单,可以生成一个新的照片库,将标题和描述发送到 MySQL,并将用户重定向到他们可以上传照片的页面.

I have a simple form that generates a new photo gallery, sending the title and a description to MySQL and redirecting the user to a page where they can upload photos.

一切正常,直到 & 符号进入等式.信息从 jQuery 模式对话框发送到 PHP 页面,然后该页面将条目提交到数据库.Ajax 成功完成后,用户被发送到上传页面,并带有一个 GET URL 告诉页面它正在上传什么专辑 --

Everything worked fine until the ampersand entered the equation. The information is sent from a jQuery modal dialog to a PHP page which then submits the entry to the database. After Ajax completes successfully, the user is sent to the upload page with a GET URL to tell the page what album it is uploading to --

$.ajax ({
    type: "POST",
    url: "../../includes/forms/add_gallery.php",
    data: $("#addGallery form").serialize(),
    success: function() {
        $("#addGallery").dialog('close');
        window.location.href = 'display_album.php?album=' + title;
    }
});

如果标题有&符号,则上传页面的标题字段无法正常显示.有没有办法为 GET 转义符?

If the title has an ampersand, the Title field on the upload page does not display properly. Is there a way to escape ampersand for GET?

谢谢

推荐答案

一般来说,您需要 URL-encode 任何不完全是字母数字的内容,当您将它们作为 URL 的一部分传递时.

In general you'll want to URL-encode anything that isn't completely alphanumerical when you pass them as parts of your URLs.

在 URL 编码中,& 被替换为 %26(因为 0x26 = 38 = & 的 ASCII 码).

In URL-encoding, & is replaced with %26 (because 0x26 = 38 = the ASCII code of &).

要在 Javascript 中执行此操作,您可以使用函数 encodeURIComponent:

To do this in Javascript, you can use the function encodeURIComponent:

$.ajax ({
    type: "POST",
    url: "../../includes/forms/add_gallery.php",
    data: $("#addGallery form").serialize(),
    success: function() {
        $("#addGallery").dialog('close');
        window.location.href = 'display_album.php?album=' + encodeURIComponent(title);
    }
});

请注意,escape 的缺点是 + 未编码,将在服务器端解码为空格,因此应避免使用 (来源).

Note that escape has the disadvantage that + is not encoded, and will be decoded serverside as a space, and thus should be avoided (source).

如果您希望在 PHP 级别执行此服务器端操作,则需要使用函数 urlencode.

If you wish to do this serverside at the PHP level, you'll need to use the function urlencode.

相关文章