POST JSON
通过web界面实现触发事件,下发json数据给设备,设备收到json数据后进行相应的处理。通过web界面按钮点击下发json数据。web界面如下:
通过点击open led会下发给设备{"id":"1","status":"on"}这样一组自定义的json数据。web页面布局以及json数据发送的jsontest.html文件内容如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button id="app" onclick="pro()">open led</button>
</body>
<script>
function pro(){
var xhr = new XMLHttpRequest()
xhr.open('POST','/action/jsontest')
xhr.setRequestHeader('Content-type','application/json;charset=UTF-8');
// send里填参数即可
xhr.send(JSON.stringify({id:"1",status:"on"}))
//监听状态变化
xhr.onreadystatechange = function() {
// if (xhr.readyState === 4&&xhr.status ===200){
if (xhr.status ===200){
// 处理响应正文responseText,多数是json数据
alert(xhr.responseText)
}
}
}
</script>
</html>
由于是向/action/jsontest通过post的方法。因此在设备端需要做如下定义
websDefineAction("jsontest",selfDefineProtocol);
/**recive json data**/
static void selfDefineProtocol(Webs *wp)
{
if(wp->input.servp){
printf("[%s] recive json data is [%s]\n",__FUNCTION__,wp->input.servp);
}
websSetStatus(wp,200);
websWriteHeaders(wp,-1,0);
websWriteEndHeaders(wp);
websDone(wp);
}
切记json数据是通过wp->input.servp获取,获取json数据后我们可以通过cjson或者objectjson库进行解析,这里只是将获取的json字符串打印输出,未通过库进行具体字段解析,有需要的可以执行进行解析。
GET JSON
通过按键获取JSON数据,界面如下,通过get json data,获取指定的uri中的json数据。
getjsontest.html页面如下:这里将method修改为GET
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button id="app" onclick="pro()">get json data</button>
</body>
<script>
function pro(){
var xhr = new XMLHttpRequest()
xhr.open('GET','/action/jsontest')
//xhr.setRequestHeader('Content-type','application/json;charset=UTF-8');
// send里填参数即可
xhr.send();
//监听状态变化
xhr.onreadystatechange = function() {
// if (xhr.readyState === 4&&xhr.status ===200){
if (xhr.status ===200){
// 处理响应正文responseText,多数是json数据
alert(xhr.responseText)
}
}
}
</script>
</html>
设备端解析到方法是get的时候返回JSON字符串
/**recive json data**/
char *json_string = "{\"name\":\"zhangsan\",\"age\":\"30\"}";
static void selfDefineProtocol(Webs *wp)
{
if(strncmp(wp->method,"POST",strlen("POST")) == 0){
if(wp->input.servp){
printf("[%s] recive json data is [%s]\n",__FUNCTION__,wp->input.servp);
}
websSetStatus(wp,200);
websWriteHeaders(wp,-1,0);
websWriteEndHeaders(wp);
websDone(wp);
}
else if(strncmp(wp->method,"GET",strlen("GET")) == 0){
websSetStatus(wp,200);
websWriteHeader(wp,"Content-Type","application/json");
websWriteEndHeaders(wp);
websWrite(wp,"%s",json_string);
websDone(wp);
}
}