HTML与Matlab APP的数据交互
Matlab APP部分
1.用的是Matlab 2020a,先在APP模块里将HTML组件拖入到界面
2.右键右上角app.UIFigure生成初始化回调函数,并且插入如下语句,其中login.html为等会要制作的登录界面
function startupFcn(app)
app.HTML.Position = [0 0 640 480];
app.HTML.HTMLSource = fullfile(pwd,'login.html');
end
2.右键右上角app.HTML生成数据改变时对接HTML的接口函数,并且插入如下语句:
function HTMLDataChanged(app, event)
data = app.HTML.Data; //接受来自HTML的数据
if length(data)==14
if data=='"CSUand123456"'
app.main=mainface();
delete(app);
else
app.HTML.Data = "账号或者密码错误!";
//该数据用于传给HTML
end
else
app.HTML.Data = "账号或者密码错误!";
end
end
HTML部分
该部分的核心是如何对接Matlab APP,在
<script type="text/javascript"> </script>
之间插入如下代码
<script type="text/javascript">
function setup(htmlComponent) {
document.getElementById("Login").addEventListener("click", function(event) {
var name = document.getElementById('Name').value;
var pwd = document.getElementById('pwd').value;
var add ='and'
htmlComponent.Data = JSON.stringify(name+add+pwd);
});//这个是监听HTML响应,然后将数据通过JSON转化为char发给Matlab APP
htmlComponent.addEventListener("DataChanged", function(event) {
document.getElementById("dataDisplay").innerHTML = htmlComponent.Data;
document.getElementById("dataDisplay").style.visibility='visible';
}); //这个是监听Matlab APP响应,获取来自Matlab APP的数据
document.getElementById("Name").addEventListener("focus", function(){
document.getElementById("dataDisplay").style.visibility='hidden'; });
//这个是监听账号输入框的focus响应事件
document.getElementById("pwd").addEventListener("focus", function(){
document.getElementById("dataDisplay").style.visibility='hidden'; });
}
//这个是监听密码输入框的focus响应事件
</script>
结果展示和代码链接
这是个动态图,会动态冒泡
如果账号密码输入有误,Matlab会返回给界面错误信息: