cocos-js http网络请求XMLHttpRequest

 
  
1.get请求  代码如下
//获取用户数据
var xhr = cc.loader.getXMLHttpRequest();//创建XMLHttpRequest对象
cc.log("Status: Send Get Request to httpbin.org");
//set arguments with ?xxx=xxx&yyy=yyy
var url ="http://xxx/game/v1/sdk/gameuser";
url=url+"?"+"access_token="+token+"&gameId="+gameid;
cc.log(url);
xhr.open("GET", url, true);//设置和服务器交互的参数
xhr.onreadystatechange = function () {		//注册回调的方法,发送成功后执行
    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
        var httpStatus = xhr.statusText;
        var response = xhr.responseText//.substring(0, 100) + "...";
        user=JSON.parse(response).datas;
        cc.log(user);
      //  cc.log("GET Response (100 chars): \n" + response);
       // cc.log("Status: Got GET response! " + httpStatus);
    }
};
xhr.send();//设置向服务器发送的数据,启动和服务器的交互

2.post请求 代码如下
 
  
 //获取用户数据
 var xhr = cc.loader.getXMLHttpRequest();
 cc.log("Status: Send Get Request to httpbin.org");
 //set arguments with ?xxx=xxx&yyy=yyy
 var url=urlrequest;
// url=url+"?"+"access_token="+userjson.access_token+"&gameId="+userjson.gameId;
 cc.log(url);

 xhr.open("POST", url);
 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 //xhr.setRequestHeader("Accept","application/json");
 xhr.onreadystatechange = function () {
     if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
         var httpStatus = xhr.statusText;
         var response = xhr.responseText//.substring(0, 100) + "...";
         user=JSON.parse(response).datas;
         cc.log(user);
         cc.log(response);
     }
 };
 cc.log(JSON.stringify(userjson));
 var i = 0;
 for(var key in userjson){
     if(i++ != 0){
         userstr += '&';
     }
     userstr += key + '=' + userjson[key];
 }
 cc.log(userstr);
 // xhr.send("gameId=11463&access_token=47790cbe07ec953951b95ef616130d58");
 xhr.send(userstr);

 
 

你可能感兴趣的:(cocos-js,cocos-js,xmlhttprequest)