問題描述
我有這個 MooTools 代碼:
I have this MooTools code:
new Request.JSON({
method: 'POST',
url: URL, /*URL TO ANOTHER DOMAIN*/
onSuccess: function(r){
callback(r);
}
}).post(data);
并且此代碼不發送 POST 請求(僅限 OPTIONS)...看看下面的代碼(效果很好):
And this code doesn't send POST requests (OPTIONS only)... Look at the code below (it works great):
var http = null,
params = Object.toQueryString(data);
try {
http = new XMLHttpRequest();
} catch (e) {
try {
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
http = null;
alert("Your browser does not support AJAX!");
}
}
}
var url = URL;
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
var jsonData = JSON.parse(http.responseText); /*OR EVAL*/
callback(jsonData);
}
};
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(params);
編輯:
試過:.setHeader('Content-Type','application/x-www-form-urlencoded');
還是什么都沒有……哪里有問題?
Tried: .setHeader('Content-Type','application/x-www-form-urlencoded');
Still nothing... Where can there be a problem?
謝謝!
推薦答案
這是因為 MooTools 將一些額外的東西與請求標頭捆綁在一起.
This is because MooTools bundles some extra stuff with the request headers.
例如.如果你的 htaccess 說:
eg. if your htaccess says:
Header set Access-Control-Allow-Origin: *
您需要像這樣制作您的請求:
you need to craft your request like that:
var foo = new Request({
url: 'http://fragged.org/Epitome/example/data/',
method: 'get',
onComplete: function (data) {
// returns an object with name and surname
new Element('div[html="{name} {surname}"]'.substitute(JSON.decode(data))).inject(document.body);
}
});
// need to remove that or CORS will need to match it specifically
delete foo.headers['X-Requested-With'];
foo.send();
這就是為什么您只能在飛行前看到 OPTIONS.它不喜歡你:)
This is why you are only seeing the OPTIONS pre-flight. It does not like you :)
您可以將 .htaccess
更改為也匹配 X-Requested-With
,這可能是一些額外的安全性".
You could change the .htaccess
to also match X-Requested-With
, which is probably some extra "security".
有關工作示例,請參閱 http://jsfiddle.net/7zUSu/1/ - 我前段時間我想對 Request https://github.com 進行更改時這樣做了/mootools/mootools-core/issues/2381 已修復.
See http://jsfiddle.net/7zUSu/1/ for a working example - I did that a while ago when I wanted to get this change to Request https://github.com/mootools/mootools-core/issues/2381 fixed.
這篇關于MooTools CORS 請求與原生 Javascript的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!