Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

xmlhttprequest - MooTools CORS request vs native Javascript

I have this MooTools code:

new Request.JSON({
  method: 'POST',
  url: URL, /*URL TO ANOTHER DOMAIN*/
  onSuccess: function(r){
    callback(r);
  }
}).post(data);

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);

EDIT:

Tried: .setHeader('Content-Type','application/x-www-form-urlencoded');
Still nothing... Where can there be a problem?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because MooTools bundles some extra stuff with the request headers.

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();    

This is why you are only seeing the OPTIONS pre-flight. It does not like you :)

You could change the .htaccess to also match X-Requested-With, which is probably some extra "security".

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...