2013-08-26 31 views
4

我有這樣的MooTools的代碼:MooTools的CORS請求VS本地JavaScript

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

而這個代碼不發送POST請求(選項只)... 看看下面的代碼(它的偉大工程):

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');
不過諾斯ing ...哪裏會有問題?

謝謝!

+2

如果它發送OPTIONS請求,這聽起來像一個[CORS預檢請求(http://stackoverflow.com/questions/8685678/cors-how-do-preflight-an-httprequest),這表明使用的是您的跨網站請求中的非簡單請求標頭。您的非Mootools代碼設置爲「Content-type:application/x-www-form-urlencoded」,但您的Mootools代碼可能不會。 – apsillers

+0

嘗試在您的mootools請求中設置「headers」選項。 – Nils

+1

嘗試:.setHeader( '內容 - 類型', '應用程序/ x-WWW窗體-urlencoded');仍然沒有......問題在哪裏? – user889349

回答

8

這是因爲MooTools的捆綁一些額外的東西與請求頭。

例如。如果您的htaccess說:

Header set Access-Control-Allow-Origin: * 

你需要你的手藝要求這樣的:

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

這就是爲什麼你只看到選項前的飛行。它不喜歡你:)

你可以改變.htaccess也匹配X-Requested-With,這可能是一些額外的「安全」。

請參閱http://jsfiddle.net/7zUSu/1/作爲一個工作示例 - 我之前做過這樣的事情,當時我想要將此更改修改爲請求https://github.com/mootools/mootools-core/issues/2381已修復。

+1

像往常一樣很好的回答!謝謝。 – user889349

+0

我不知道該如何謝謝你;這很可能爲我節省了幾個小時的頭髮。 –

0

你說的(唯一的選擇)是什麼意思?這兩個示例都發送POST請求,唯一的區別在於Accept請求標頭。

MooTools的發送Accept: application/json,而本機發送Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

這可能會影響服務器如何響應。