使用 XMLHttpRequest 和表单调用 URL 有什么区别?

Whats the difference between calling a URL using XMLHttpRequest and a Form?

我正在使用静态 html/javascript 页面(没有 php,等等)

我有一个静态 HTML 网页。当页面加载时,它向另一个域上的目标服务器发出 XMLHttpRequest,等待响应,并解析响应 JSON.

  function executeRequest() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        var response = JSON.decode(xhttp.responseText);
        alert(response.access_token)
        alert(response.expires_in)
      }
    };
    var tmpURL = "https://target.url.com/oauth2/access_token"
    xhttp.open("POST", tmpURL, true);
    xhttp.send();
  }

XMLHttpRequest cannot load [target.url.com] No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://local.url.com' is therefore not allowed access.

要排除 CORS 的问题,我可以使用表单请求 URL。当用户点击提交按钮时,会带来一个成功的响应。

<form method="POST" action="https://target.url.com/oauth2/access_token">
  ... form inputs here
  <input type="submit" value="Submit form">
</form>

为什么目标服务器对 xmlHttpRequest 的响应与对表单的响应不同?

您遇到了 CORS 问题。

XMLHttpRequests 受 CORS 规则约束。

<form method="POST" action="http://xxx"> post 完全使用 HTML 完成的不受 CORS 规则约束。

就这么简单。

允许此跨源表单 post 的部分原因是浏览器将更改浏览器 window 以显示来自表单 post 的响应,因此跨源站点控制接下来发生的事情。 XMLHttpRequest 不是这种情况,在 XMLHttpRequest 之后请求页面控制接下来发生的事情,因为没有页面自动加载或显示。因此,使用 XMLHttpRequest 比使用 post.

更容易引起恶作剧

请参阅 Cross Domain Form POSTing 了解更多说明。