【问题标题】:Is there a way to send params inside params in ajax call (vanillaJS) [duplicate]有没有办法在ajax调用(vanillaJS)中的参数中发送参数[重复]
【发布时间】:2021-04-07 12:56:13
【问题描述】:

上下文

我正在为基于grapesjs-mjml 的电子邮件模板构建器构建一个保存/加载系统。我将 MJML 代码保存在 BDD (MySQL) 中。

我当前的代码

我正在通过一个看起来像这样的 ajax 调用发送我的模板名称和我的模板 MJML 代码

let params = "name="+template_name + "&html="+template_mjml;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "save.php", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // doing stuffs when it's saved
  }
};
xhttp.send(params);

在服务器端,我用标准的 $_POST['html'] 捕获了 html

我的问题

有时,我的html 参数中有网址(例如,它可能是链接)。在这些网址中,有一些&,这意味着我的$_POST['html'] 没有读取整个参数:它在我的html 代码的第一个& 之前停止

我的肮脏解决方案

在我的客户端,我添加了一个html = html.replaceAll('&','//amp;'),我正在服务器端执行反向功能。哪一个,我在我的“html”参数中删除了所有&,但这不是很好......

我想知道你们中是否有人知道更好/更好的解决方案?

【问题讨论】:

  • 查看链接问题的答案。您总是必须对 URI 值进行编码,例如使用 encodeURIComponent。事实上,密钥也需要编码,但如果您知道密钥没有任何编码会改变的字符(例如namehtml 不会),您可以跳过它。
  • 在请求前后对数据进行编码和解码。使用encodeURI()在您的ajax调用中对其进行编码,并使用htmlspecialchars_decode()在php中决定

标签: javascript php ajax


【解决方案1】:

您应该使用encodeURIComponent()。这将正确编码特殊字符。

let params = "name=" + encodeURIComponent(template_name) + "&html=" + encodeURIComponent(template_mjml);

【讨论】:

  • 嗯...我已经尝试过了,但它不起作用,现在它起作用了...谢谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多