工作中遇到的由js调取本地某C+而写的插件,解决跨域问题获取该插件从usb接口中获取的数据,记录文本,后续补充
webSocket调用方式(首先支持跨域要插件支持webSocket)
try {
var postData = JSON.stringify({
"test": "one",
"items": [
{
"code": "000801000000000000051822",
"assetName": "O测试",
"assetSKUName1": "oneTestName",
"assetSKUName2": "twoTestName",
"vendor": "广州XXXX有限公司"
}
]
});
if ('WebSocket' in window) {
wsreport = new WebSocket("ws://127.0.0.1:8083/print");
} else if ('MozWebSocket' in window) {
wsreport = new MozWebSocket("ws://127.0.0.1:8083/print");
} else {
alert("谷歌和火狐浏以外的浏览器暂时不支持!")
}
wsreport.onopen = function () {
var param = postData;
wsreport.send(param);
};
wsreport.onmessage = function (evt) {
var data = evt.data;
console.log("收到数据..." + data);
}
wsreport.onclose = function () {
console.log("连接已关闭...");
};
wsreport.onerror = function (evt) {
console.error("端口通信失败!", evt);
alert("打印机连接端口通信失败")
};
} catch (e) {
console.error("连接端口服务异常:", e)
alert("打印机连接端口通信失败")
}
$.ajax({
url: "http://localhost:8083/print",
data: JSON.stringify({
"test": "two",
"items": [
{
"code": "000801000000000000051822",
"assetName": "O测试",
"assetSKUName1": "TwoSkuName",
"assetSKUName2": "TwoSkuName2",
"vendor": "广州XXXXXX有限公司"
}
]
}),
dataType: "json",
type: "POST",
crossDomain: true,
async: false,
cache: false,
timeout: 2000,
success: function (rs) {
console.log(JSON.stringify(rs));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status ==200 || XMLHttpRequest.statusText.indexOf("OK") == 0) {
console.log("打印连接成功");
}else if( XMLHttpRequest.status == 404 || XMLHttpRequest.statusText.indexOf("NetworkError") == 0){
alert("打印失败:请检查“打印客户端”是否配置运行正常。");
}else {
alert("打印标签失败:" + XMLHttpRequest.statusText);
}
}
});
|