wx.request请求

刚刚开始研究微信小程序。记录一下wx.request请求。

wxml:

<text user-select=”false” >选择服务器:</text>
<!– 绑定form提交事件 –>
<form bindsubmit=”onlineServer“>
<input name=”server” type=”text” value=’10.10.0.21′ style=”display: none;”/>
<!– 绑定checkbox-group提交事件 –>
    <checkbox-group bindchange=”chkchange” >
<!– 把label和checkbox绑定管理。这样点击label也可以选中checkbox –>
        <label style=”display: flex;”>
            <view>
                <checkbox  value=”110.112.13.38″ />
            </view>
                <view >10.112.13.38</view>
        </label>
        <label style=”display: flex;”>
            <view>
                <checkbox  value=”10.112.13.71″ />
            </view>
                <view >10.112.13.71</view>
        </label>
    </checkbox-group>
<!– 定义button为提交按钮 –>
    <button type=”primary” size=”mini” form-type=”submit”>提交</button>
</form>
js:
//定义变量
var nginxchk;
Page({
//定义事件函数,把checkbox的所有值都放到变量nginxchk中。e表示checkbox
chkchange(e){
        nginxchk=e.detail.value;
    },
//定义提交函数。e表示form对象。
onlineServer(e){
//发起wx.request请求
        wx.request({
                       //填写请求url
            url: ‘https://xx.hsxwion.com/proxys/wx_status.php’,
                      //根据后端处理方式填写。
            method:’POST’,
                      //重点:如果采用form提交,就按照如下方式。默认是application/json.
            header:{ “Content-Type”: “application/x-www-form-urlencoded” },
                       //重点:格式采用json格式。我这里传递两个键值对。server和nginxchk。nginxchk是数组。
            data:{
                “server”:e.detail.value.server,
                “nginxchk”:nginxchk
            },
            success:(res)=>{
              console.log(res.data)
            }
          })
    },
})
后端PHP处理:
 //该文件用于XXXX模块中的查看服务器状态
        require ‘../base.php’;
        //前端把默认服务器ip地址传递过来。先获取server的ip地址
        $server=$_POST[“server”];
        //获取要操作的服务器列表
        $nginxchk=$_POST[“nginxchk”];

//把字符串变成数组。

        $arr=explode(‘,’,$nginxchk);
       //后面根据自己业务进行操作即可。

wx.request请求》有2个想法

  1. method如果采用POST,最好采用header:{ “Content-Type”: “application/x-www-form-urlencoded” }。因为默认是application/json。后端服务器要对传递来的json进行处理。
    参见官方说明:
    data 参数说明
    最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:

    对于 GET 方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)
    对于 POST 方法且 header[‘content-type’] 为 application/json 的数据,会对数据进行 JSON 序列化
    对于 POST 方法且 header[‘content-type’] 为 application/x-www-form-urlencoded 的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)

回复 匿名 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注