<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script>
$.get("http://example.com/", function(data) {
alert(data);
});
</script>
它对那个URL做一个OPTIONS请求,然后回调永远不会被调用任何东西。
当它不是跨域时,它工作得很好。
jQuery不应该只是调用一个<script>节点,然后在它加载时做回调吗?我知道我将无法得到的结果(因为它是跨域),但这是可以的;我只想让电话接通。这是bug,还是我做错了什么?
根据MDN,
Preflighted requests
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP OPTIONS request header to the resource on the other
domain, in order to determine whether the actual request is safe to
send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET or POST. Also, if POST is used to send
request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as
X-PINGOTHER)
我也有同样的问题。我的修复是添加头到我的PHP脚本,只有在开发环境中才会出现。
这允许跨域请求:
header("Access-Control-Allow-Origin: *");
这告诉preflight请求,客户端可以发送任何它想要的头文件:
header("Access-Control-Allow-Headers: *");
这样就不需要修改请求了。
如果您的开发数据库中有可能泄露的敏感数据,那么您可能要三思。
只需将“application/json”更改为“text/plain”,不要忘记json .stringify(request):
var request = {Company: sapws.dbName, UserName: username, Password: userpass};
console.log(request);
$.ajax({
type: "POST",
url: this.wsUrl + "/Login",
contentType: "text/plain",
data: JSON.stringify(request),
crossDomain: true,
});