MooTools CORS request vs native Javascript(MooTools CORS 请求与原生 Javascript)
问题描述
我有这个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MooTools CORS 请求与原生 Javascript
基础教程推荐
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01