共计 2456 个字符,预计需要花费 7 分钟才能阅读完成。
个别服务端接口的参数都是 json
格局,然而因为某些起因当入参须要 XML
格局的怎么办? 如装置在本地零碎的 ic 卡驱动服务须要写卡操作的接口入参为 xml 格局:
现有参数,data 项能够有多个:
var json = {
iccard: {
operation: "writeCard",
data:[{Id:1, Number:10001},...]
}
};
理论 XML 格局:
<iccard>
<operation>writeCard</operation>// 接口操作标识 writeCard 为写卡。<data>
<Id>1</Id>
<Number>10001</Number>
</data>
<data>
<Id>2</Id>
<Number>10002</Number>
</data>
<data>
<Id>3</Id>
<Number>10003</Number>
</data>
...
</iccard>
一种形式是把 json 数据通过正则把参数全都转成有闭合标签尖括号 <xxx> 的字符串。其实是能够应用一个更简便、稳固的办法,应用 x2js
库把 json
转成 xml
格局,下载安装 x2js
库并导入:
import x2js from "x2js";
var x2jsxml = new x2js();
if(iccardApi=="writeCard"){
var json = {
iccard: {
operation: "writeCard",
data: data.param
}
};
data.param = x2jsxml.js2xml(json);// 转成 xml 格局
}
在申请之前对入参进行解决后把 data
带到入参中,应用 Promise 和 Ajax
封装一个专门解决 ic 卡 XML
接口对接的 CCardAjax
函数
ICCard.js:
"use strict";
import {Loading} from "element-ui";
import x2js from "x2js";
var x2jsxml = new x2js();
const baseUrl = "http://localhost:8888/iccard"; //ic 卡控件地址
let ICCardObj = {};
//iccardApi(read 读卡,writeCard 写卡)
ICCardObj.ajax = (iccardApi, data, that) => {
var isHideErrorTip = false;
if ("isHideErrorTip" in data) { // 是否不显示未插卡提醒
isHideErrorTip = data.isHideErrorTip;
delete data.isHideErrorTip;
}
if(iccardApi=="writeCard"){
var json = {
iccard: {
operation: "writeCard",
data: data.param
}
};
data.param = x2jsxml.js2xml(json);
}
var loading = Loading.service({
lock: true,
text: "正在执行操作...",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.3)"
});
return new Promise((resolve, reject) => {
$.ajax({
url: baseUrl + "/" + iccardApi,
type: "GET",
data: data,
success: function(res) {loading.close();
if (res.resultCode == "error") { // 未插卡 读卡失败
reject(res);
if (!isHideErrorTip) {
that.$message({
title: "正告",
message: "请插卡!",
type: "error"
});
}
} else {resolve(res.dataList);
console.log("读取胜利");
}
},
error: function(res) {// 读卡失败
loading.close();
if (!isHideErrorTip) {
that.$message({
title: "正告",
message: "未启动 IC 卡控件,请先正确启动",
type: "error"
});
}
reject(res);
}
});
});
};
export default ICCardObj;
把 ICCardAjax
绑定到 vue 原型链上供各组件应用:
import ICCardAjax from "@/assets/js/ICCard.js";
Vue.prototype.ICCardAjax = ICCardAjax;
组件中应用:
// 读卡 - 查问
readICCard() {return new Promise((resolve, rej) => {this.ICCardAjax.ajax("read", {}, this)
.then(res => {resolve(res);
// 读卡胜利
...
})
.catch(res => {rej(res);
...
// 读卡失败
});
});
},
writeCard(data) {return new Promise((resolve, rej) => {this.ICCardAjax.ajax("writeCard", { param: data}, this)
.then(res => {resolve(res);
console.log("写卡胜利");
})
.catch(res => {rej(res);
this.$message({
message: "写卡失败",
type: "error"
});
});
});
},
// 写个卡
querySubmit() {
this.writeCard([
{
Id: 4,
Number: 111
},
{
Id: 4,
Number:222
},
{
Id: 4,
Number: 333
}
]).then(res => {
this.$message({
message: "写查询卡胜利!",
type: "success"
});
this.readICCard();});
},
```
正文完