PHP base64 编码 post 请求

PHP base64 encode post request

简而言之:

<form method="post" action="">
    <textarea name="foo">bar</textarea>
</form>

我想 POST foo 的值作为 base64 编码(不使用 ajax 以节省时间)。

详细:

您不需要使用 Ajax,您可以使用表单的 onsubmit 事件编写一个 javascript 处理程序,将数据编码为隐藏输入,并一起发送与表格(注意原来的textarea没有name,所以不会在POST中发送)。

function encodeSql() {

    var e = document.getElementById('sql');
    var t = document.getElementById('sql_base64');
    t.value = encodeToBase64Somehow(e.value);
    return true;
}

<form ... onsubmit="return encodeSql()">
    <textarea id="sql">...</textarea>
    <input type="hidden" name="sql_base64" id="sql_base64" />
</form>

您可以在提交表单之前将文本值转换为 Base64 字符串,而无需使用 Ajax 使用 window.btoa

var str = document.getElementById("foo").value;
var enc = window.btoa(str);

The btoa() method encodes a string in base-64.
This method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.

有关 btoa 的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa