当前位置:   article > 正文

cocosCreator 网络请求接口(json和表单两种)_cocos creator json

cocos creator json
  1. import { Component, loader } from "cc";
  2. const url_http = "https://xqapi.haoyingsheng.top/api";
  3. export default class HttpUtil {
  4. /**
  5. * 请求协议的方法
  6. * @param path 请求接口的路径
  7. * @param params 参数
  8. * @param callBack 回调函数
  9. */
  10. public static get(path, params, callBack) {
  11. var requestUrl = url_http + path;
  12. var xhr = loader.getXMLHttpRequest();
  13. // var data=self.paramData(params);
  14. var data = params;
  15. let param = '?';
  16. for (var key in data) {
  17. var paramStr = key + "=" + data[key];
  18. if (param == "") {
  19. param += paramStr;
  20. } else {
  21. param += "&" + paramStr;
  22. }
  23. }
  24. xhr.open("GET", requestUrl + param);
  25. xhr.timeout = 5000;//
  26. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
  27. xhr.onreadystatechange = function () {
  28. if (xhr.readyState === 4 && xhr.status == 200) {
  29. var respone = xhr.responseText;
  30. console.log('响应参数')
  31. console.log(respone)
  32. callBack(JSON.parse(respone));
  33. }
  34. };
  35. xhr.send();
  36. }
  37. public static POST(url, param: object = {}, callback) {
  38. url = url_http+url;
  39. var xhr = loader.getXMLHttpRequest();
  40. let dataStr = '';
  41. Object.keys(param).forEach(key => {
  42. dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
  43. })
  44. if (dataStr !== '') {
  45. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  46. }
  47. xhr.open("POST", url, true);
  48. // 第一种表单提交
  49. // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  50. // 第二种 json提交
  51. xhr.setRequestHeader("Content-Type", "application/JSON");
  52. xhr.onreadystatechange = function () {
  53. if (xhr.readyState === 4) {
  54. let response = xhr.responseText;
  55. if (xhr.status >= 200 && xhr.status < 300) {
  56. let httpStatus = xhr.statusText;
  57. // callback(true, JSON.parse(response));
  58. callback(true, response);
  59. } else {
  60. callback(false, response);
  61. }
  62. }
  63. };
  64. // 第一种表单提交 和上面配合使用
  65. // xhr.send(JSON.stringify(dataStr));
  66. // 第二种 json提交 和上面配合使用
  67. xhr.send(JSON.stringify(param));
  68. }
  69. }
  70. function ccclass(arg0: string) {
  71. throw new Error("Function not implemented.");
  72. }

自己做的小游戏感兴趣可以扫码体验,可以交流游戏

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/152651?site
推荐阅读
相关标签
  

闽ICP备14008679号