unity3d和php后台简单交互--二

上次我们讨论了u3d和php的简单交互,现在我们接着讨论u3d和php交互,这里我们讨论的是php的后台大家可以延伸为其他语言。在实现的开发中我们很少通过发送字符或者字段到服务器上的,我们一般会请求包装成json或者xml的形式发送到服务器当中去。这样的好处是便于扩展维护,很多第三方服务比如推送等都是要我们构造json格式的数据向服务器发送的。我们现在来做一个请求玩家交易行的功能。

  把我们上篇做好的简单分页控件导入新的u3d工程中,并添加几个按钮控件,效果如图:

 

好了一个简单的商行搞好了。我们编写商行的代码并绑定到商行上。

复制代码
  1 using UnityEngine;
  2 using System.Collections;
  3 using UnityEngine.UI;
  4 using Pagination;
  5 using System.Collections.Generic;
  6 using System.Text;
  7 using System;
  8 using LitJson;
  9 using System.ComponentModel;
 10 using System.Reflection;
 11 
 12 /// <summary>
 13 /// 装备位置
 14 /// </summary>
 15 public enum EqmtPos
 16 {
 17     [DescriptionAttribute("-1")]
 18     All,            //所有
 19     [DescriptionAttribute("0")]
 20     Helmet,         //头盔
 21     [DescriptionAttribute("1")]
 22     Clothing,       //衣服
 23     [DescriptionAttribute("2")]
 24     Necklace,       //项链
 25     [DescriptionAttribute("3")]
 26     Bracelet,       //手镯
 27     [DescriptionAttribute("4")]
 28     Pants,          //裤子
 29     [DescriptionAttribute("5")]
 30     Shoes,          //鞋子
 31 }
 32 
 33 public class PageExsample : MonoBehaviour
 34 {
 35     string urlstr = "http://localhost:8081/phptest/paging.php";
 36     EqmtPos eqtpos = EqmtPos.All;
 37     int pSize = 0;
 38     void Awake()
 39     {
 40         pSize = GetComponent<Paging>().pageSize;
 41         //实例化表头
 42         GetComponent<Paging>().headers = new List<Header>(new Header[] {
 43             new Header("物品", 60),
 44             new Header("名称", 50),
 45             new Header("等级", 60),
 46             new Header("出售人", 50),
 47             new Header("售价", 50),
 48         });
 49 
 50         //实例化分页委托
 51         GetComponent<Paging>().pagehandler = new Paging.PageHandler((int _page) =>
 52         {
 53             StartCoroutine(GetPageData(_page));
 54         });
 55 
 56         //实例化数据填充委托
 57         GetComponent<Paging>().fullDatahandler = OnFullData;
 58     }
 59 
 60     /// <summary>
 61     /// 获取全部装备
 62     /// </summary>
 63     public void OnGetAllData()
 64     {
 65         eqtpos = EqmtPos.All;
 66 
 67         GetComponent<Paging>().SendMessage("OnPage", 1);
 68     }
 69 
 70     /// <summary>
 71     /// 获取衣服
 72     /// </summary>
 73     public void OnGetClothingData()
 74     {
 75         eqtpos = EqmtPos.Clothing;
 76 
 77         GetComponent<Paging>().SendMessage("OnPage", 1);
 78     }
 79 
 80     /// <summary>
 81     /// 获取裤子
 82     /// </summary>
 83     public void OnGetPantsData()
 84     {
 85         eqtpos = EqmtPos.Pants;
 86 
 87         GetComponent<Paging>().SendMessage("OnPage", 1);
 88     }
 89 
 90     /// <summary>
 91     /// 获取服务器数据
 92     /// </summary>
 93     /// <param name="_page">当前页</param>
 94     /// <returns></returns>
 95     IEnumerator GetPageData(int _page)
 96     {
 97         JsonData postData = new JsonData();
 98         postData["curPage"] = (_page - 1) * pSize;
 99         postData["pageSize"] = pSize;
100         postData["pos"] = GetEnumDescription(eqtpos);
101 
102         string jsnStr = postData.ToJson();
103 
104         WWWForm form = new WWWForm();
105         var headers = form.headers;
106 
107         headers["Content-Type"] = "application/json";
108         headers["Accept"] = "application/json";
109 
110         WWW www = new WWW(urlstr, Encoding.UTF8.GetBytes(jsnStr), headers);  
111 
112         yield return www;
113 
114         if(www.isDone)
115         {
116             if(www.error == null)
117             {
118                 //解析json
119                 JsonData jsonData = JsonMapper.ToObject(www.text);
120                 List<List<string>> dataTable = new List<List<string>>();
121 
122                 Double sz = Double.Parse(jsonData[0]["itemCount"].ToString()) / pSize;
123 
124                 GetComponent<Paging>().pageCount = (int)Math.Ceiling(sz);   //重新设置页数
125 
126                 for (int i = 1; i < jsonData.Count; i++)
127                 {
128                     List<string> strList = new List<string>();
129 
130                     strList.Add(jsonData[i]["ItemName"].ToString());
131                     strList.Add(jsonData[i]["ItemImage"].ToString());
132                     strList.Add(jsonData[i]["LEVEL"].ToString());
133                     strList.Add(jsonData[i]["Sellers"].ToString());
134                     strList.Add(jsonData[i]["Price"].ToString());
135 
136                     dataTable.Add(strList);
137                 }
138 
139                 GetComponent<Paging>().SetDataTable(dataTable);     //重新加载数据
140                 //print(www.text);
141             }
142         }
143 
144     }
145 
146     /// <summary>
147     /// 填充策略
148     /// </summary>
149     /// <param name="_itemObj">列表对象</param>
150     /// <param name="_dataList">列表数据</param>
151     void OnFullData(GameObject _itemObj, List<string> _dataList)
152     {
153 
154         string str = string.Format("arms/{0}", _dataList[1].Substring(0, _dataList[1].LastIndexOf(".")));
155         var tex2d = Resources.Load(str, typeof(Texture2D)) as Texture2D;
156 
157         if (tex2d != null)
158         {
159             var sprite = Sprite.Create(tex2d, new Rect(0, 0, 64, 64), Vector2.zero);
160             if (sprite != null)
161             {
162                 var itemimage = _itemObj.transform.FindChild("ItemImage");
163                 if (itemimage != null)
164                 {
165                     itemimage.GetComponent<Image>().sprite = sprite;
166                 }
167             }
168         }
169 
170         _itemObj.transform.FindChild("ItemName").GetComponent<Text>().text = _dataList[0];
171         _itemObj.transform.FindChild("Level").GetComponent<Text>().text = _dataList[2];
172         _itemObj.transform.FindChild("Sellers").GetComponent<Text>().text = _dataList[3];
173         _itemObj.transform.FindChild("Price").GetComponent<Text>().text = _dataList[4];
174     }
175 
176     public static string GetEnumDescription(Enum enumSubitem)
177     {
178         string strValue = enumSubitem.ToString();
179 
180         FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue);
181         System.Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
182         if (objs == null || objs.Length == 0)
183         {
184             return strValue;
185         }
186         else
187         {
188             DescriptionAttribute da = (DescriptionAttribute)objs[0];
189             return da.Description;
190         }
191 
192     }
193 }
复制代码
View Code

xml,json和php通讯要通过php的输入流才能获取参数file_get_contents('php://input');

以下是服务端代码

 1 <?php
 2     /****************************************************************************
 3     *    作者:    
 4     *    日期:    2016-09-12
 5     *    版本:    v1.0
 6     *    说明: 测试
 7      ****************************************************************************/
 8 
 9     include_once "dbconfig.php";
10     
11     $dbcfg = new dbconfig();
12 
13     $test = @file_get_contents('php://input');
14     $r = json_decode($test);
15     $items;
16 
17     if(isset($r->{"curPage"})
18         && isset($r->{"pageSize"})
19         && isset($r->{"pos"}))
20     if(true)
21     {
22         $sql = "SELECT id,ItemName, ItemImage, LEVEL, Sellers, Price, Pos FROM    pagination where 1=1";
23         if($r->{"pos"} != -1)
24         {
25             $sql .= " and pos=".$r->{"pos"};
26         }
27         $sql .= " ORDER BY id LIMIT ";
28         $sql .= $r->{"curPage"}.",".$r->{"pageSize"};
29 
30         $sqlCount = "select count(1) as itemCount from pagination where 1=1";
31         if($r->{"pos"} != -1)
32         {
33             $sqlCount .= " and pos=".$r->{"pos"};
34         }
35 
36         $dbcfg->execute("SET NAMES 'UTF8'");
37         $dbcfg->do_query($sqlCount, "get_count_item");
38         if($dbcfg->do_query($sql, "page_callback") > 0)
39         {
40             echo json_encode($items);
41         }
42     }
43     else
44     {
45         echo "fail";
46     }
47 
48     function get_count_item($row)
49     {
50         global $items;
51         $items[] = array(
52             "itemCount"=> $row["itemCount"],
53         );
54     }
55 
56     function page_callback($row)
57     {
58         global $items;
59         $items[] = array(
60             "ItemName"=>$row["ItemName"],
61             "ItemImage"=>$row["ItemImage"],
62             "LEVEL"=>$row["LEVEL"],
63             "Sellers"=>$row["Sellers"],
64             "Price"=>$row["Price"],
65             );
66     }
67 
68 ?>
View Code

好了一个简单的商行搞定了。我们看看效果吧。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rain_love_snow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值