飞利浦·斯塔克|Cocos Creator中快速实现HTTP( 二 )


   
  ;
  xhr.onerror = function (err) {
    callback && callback(-1 null \"Network error\");
  ;
  xhr.send();
  return xhr;

以POST方式向一个URL请求 , 返回一个JSON数据 , 结果以异步的方式返回:export function postJson(url: string data: object | string callback: (statusCode: number resp: object | null respText: string) => any): XMLHttpRequest {
  let xhr = new XMLHttpRequest();
  xhr.open(\"POST\" url true);
  xhr.setRequestHeader(\"Content-Type\" \"applicationjson;charset=utf-8\");
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      let resp = null;
      try {
        if (xhr.responseText != \"\") {
          resp = JSON.parse(xhr.responseText);
       
     
      catch (e) {
     
      callback && callback(xhr.status resp xhr.responseText);
   
  ;
  xhr.onerror = function (err) {
    callback && callback(-1 null \"Network error\");
  ;
  var text = typeof (data) == \"string\" ? data :JSON.stringify(data);
  xhr.send(text);
  return xhr;

总结有了以上几个函数之后 , 游戏中的大多数HTTP协议都能够应对了 。