cocos2d-js跨域訪問問題,cocos2d-js請求網路資料
阿新 • • 發佈:2019-01-01
下面是cocos2d-js請求網路資料的程式碼:
var HttpRequest = { /* * 網路請求之GET * url 請求的網路地址 * callback 回撥引數 * */ GET:function(url,callback){ var xhr = cc.loader.getXMLHttpRequest(); xhr.open("GET",url,true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) { err = false; }else{ err = true; } var response = xhr.responseText; callback(err,response); }; xhr.send(); }, /* * 網路請求之POST * url 請求的網路地址 * params 請求引數 ("id=1&id=2&id=3") * callback 回撥引數 * */ POST:function(url,params,callback){ var nums = arguments.length if(nums == 2){ callback = arguments[1]; params = ""; } var xhr = cc.loader.getXMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8"); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) { err = false; }else{ err = true; } var response = xhr.responseText; callback(err,response); }; xhr.send(params); } } //EXMAPLE /* HttpRequest.POST("http://127.0.0.1:3000/test","id=1&ids=2", function(err,data){ if(err){ //錯誤處理 }else{ cc.log(data); } }) */
但是,請求網路出現了:No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
這是因為瀏覽器不能跨域訪問,我們在服務端找到這個要請求的檔案:設定一下header
<?php
header("Access-Control-Allow-Origin : *");
echo "I Love you"
?>
這樣,就成功返回了資料?但是!!!,沒有成功,暈,原因是這個php呼叫header之前不能有任何輸出,必須改編碼為UTF-8 無rom格式,弄了一晚上卡在這個點上!!!