在开发过程中需要用到ajax的post方式提交,并且存在跨域问题,由于一些机制的问题,不打算用XMLHttpRequest 对象来实现。从网上搜索了资料,找到了一个解决方案。 需要注意的是要设置一个参数,如下说明,要将 $.support.cors 设置为 true;
$.support.cors = true;
$.ajax({
// The 'type' property sets the HTTP method.
// A value of 'PUT' or 'DELETE' will trigger a preflight request.
type: 'POST',
// The URL to make the request to.
url: 'http://updates.html5rocks.com',
// The 'contentType' property sets the 'Content-Type' header.
// The JQuery default for this property is
// 'application/x-www-form-urlencoded; charset=UTF-8', which does not trigger
// a preflight. If you set this value to anything other than
// application/x-www-form-urlencoded, multipart/form-data, or text/plain,
// you will trigger a preflight request.
contentType: 'text/plain',
xhrFields: {
// The 'xhrFields' property sets additional fields on the XMLHttpRequest.
// This can be used to set the 'withCredentials' property.
// Set the value to 'true' if you'd like to pass cookies to the server.
// If this is enabled, your server must respond with the header
// 'Access-Control-Allow-Credentials: true'.
withCredentials: false
},
headers: {
// Set any custom headers here.
// If you set any non-simple headers, your server must include these
// headers in the 'Access-Control-Allow-Headers' response header.
},
success: function() {
// Here's where you handle a successful response.
},
error: function() {
// Here's where you handle an error response.
// Note that if the error was due to a CORS issue,
// this function will still fire, but there won't be any additional
// information about the error.
}
});
并且后端代码,需要利用 CORS,添加一个头 就可以允许来自 某个网站的请求,下面代码是在PHP中的 hander() 设置,“*”号表示允许任何域向我们的服务端提交请求:
header('Access-Control-Allow-Origin:*');
参考网址: http://www.cnblogs.com/Darren_code/p/cors.html http://www.html5rocks.com/en/tutorials/cors/