XMLHttpRequest POST 参数编码

XMLHttpRequest POST parameter encoding

我想提交 POST 请求,同时传递 url 等参数。 我有以下脚本,但它不起作用。

var params = "param1="+param1_value+"&url="+url_value;

var xhr = new XMLHttpRequest();
xhr.open("POST", action_url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
  if(xhr.readyState == 4 && xhr.status == 200){
    console.log("Done");
  }
}
xhr.send(params);

假设 url_value 是这样的:

https://www.domain.com/blah?param=&email=domain%40email%2Ecom&blah=1234

这个脚本有什么问题?

您在尝试访问另一个 domain/website 时可能会遇到问题。接收方必须在其 return 消息中包含 Access-Control-Allow-Origin header。

您或许可以在 this answer 中找到您的解决方案。

看看这个question/answer - Should I URL-encode POST data?

url_value 的示例值正在使用 HTML Entity Code。由于值中的 & 符号,它被作为多个值发送。您可能需要 URL 对其进行编码,使其看起来像这样

https%3A%2F%2Fwww.domain.com%2Fblah%3Fparam%3D%26email%3Ddomain%40email.com%26blah%3D1234

您缺少对 url 字符串值的引号,请按如下提示参数字符串

var 参数 = "param1='"+param1_value+"'&url='"+url_value+"'";