提交数据是系统中最常见的功能,如果是WEB,常用的几种方式不外乎是form表单的submit,又或者是jquery的ajax等,都跟表单有关。
如果用Electron做桌面软件方式,虽然也可以用jQuery的方式,但存在跨域问题,虽然也可以通过配置文件的属性webSecurity解决(未测试,网上都是这样说的),但是总感觉不太好,所以就研究了下官网的文档,发现用NET就能可以提交数据,步骤如下。
一、前端html 表单
<form id="hmForm">
<input type="text" id="name" name="name" value=""/>
<input type="text" id="age" name="age" value=""/>
<input type="button" value="提交数据" id="save"/>
</form>
二、引入jQuery
这里主要为了方便格式化表单内的数据,以及使用DOM的选择操作,这块功能jQuery真的很方便,如果自己写也可以不需要引入。
<script src="./js/jquery.min.js"></script>
三、JS
const electron = require('electron');
const remote ={dialog,net}= electron.remote;
let childWindow = remote.getCurrentWindow();
$(function(){
$("#save").click(function(){
post("http://127.0.0.1:8080/demo/test.do","hmForm","saveCallback");
});
});
//数据提交成功或者失败的回调函数,具体内容根据实际情况写
function saveCallback(result){
ele_alert("提示信息","这是个回调函数");
}
//将后端的地址转换为Electron的net需要的参数
function getOptions(url){
let protocol = 'http:';
let host=null,path=null;
if(url.indexOf("https:")==0){
protocol="https:";
}
url = url.replace(/^(http:\/\/|https:\/\/)/,"");
const i = url.indexOf("/");
host = url.substring(0,i);
path = url.substring(i);
const arr = host.split(":");
const options = {
method: 'POST',
protocol: protocol,
host: host,
path: path
};
if(arr.length>1){
options.port = arr[1];
}
return options;
}
//Electron自带的对话框
function ele_alert(title,message,callbackName,options){
childWindow.focus();
dialog.showMessageBox(childWindow,{
title:title,
message:message
}).then(result=>{
Object.assign(result,options);
eval(callbackName)(result);
}).catch(err=>{
console.log(err);
});
}
//POST主函数
function post(url,formId,callbackName){
let data = $("#"+formId).serialize();
const option = this.getOptions(url,true);
let request = net.request(option);
request.setHeader("Content-Type","application/x-www-form-urlencoded");
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (result) => {
console.log(`BODY: ${result}`)
//这里的result就是java后台返回的内容,我这里的格式如{succeed:true,code:"这里是提示信息,成功或者失败"}
const rt = JSON.parse(result);
ele_alert("提示信息",rt.code,callbackName,rt);
})
response.on('end', () => {
console.log('响应中已无数据')
})
});
request.on('error', (e) => {
alert("出错了:${e.message}");
});
request.write(data);
request.end();
}
四、配置文件main.js
const { app, BrowserWindow} = require('electron')
function createWindow () {
// 创建浏览器窗口
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule:true //注意要加上这行
}
})
// 并且为你的应用加载index.html
win.loadFile('index.html');
}
app.whenReady().then(createWindow)
效果如下所示
点击“提交数据”按钮,弹出数据提交成功对话框,并且Eclipse的控制台显示了提交过去的数据,说明后台接收成功。
点击确定按钮后,运行回调函数,由于我这里只写了个弹出框,所以就只弹出一个对话框,如下
上面的几个方法只是简单的写了下,各位可以使用jQuery模式重新封装,以便后面使用