MooTools CORS 请求与原生 Javascript [英] MooTools CORS request vs native Javascript

查看:17
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆