2016-03-05 60 views
0

我无法访问index.html中index.js中的变量'dps'声明,使用npm start(用于启动电子应用程序) 我能够访问我的sql并获取index.js中的数据,并且我想要显示index.html(使用nodeJs和Electron) 'dps'是指具有mysql数据的js对象我无法访问index.html中index.js中的变量'dps'声明,使用npm start

//我index.js文件有

var app = require('app'); 
var dps = [{x:1,y:2}]; 
// Module to create native browser window. 
var BrowserWindow = require('browser-window'); 
var mainWindow = null; 
var dps = [{x:1,y:2}]; 
var mysql = require('mysql'); 

// Quit when all windows are closed. 
app.on('window-all-closed', function() { 
    if (process.platform != 'darwin') { 
    app.quit(); 
    } 
}); 

app.on('ready', function() { 

    // Create the browser window. 
    mainWindow = new BrowserWindow({ width: 800, height: 600 }); 
    mainWindow.loadUrl('file://' + __dirname + '/index.html'); 
    // Open the devtools. 
    // mainWindow.openDevTools(); 
    // Emitted when the window is closed. 
    mainWindow.on('closed', function() { 
    // Dereference the window object, usually you would store windows 
    // in an array if your app supports multi windows, this is the time 
    // when you should delete the corresponding element. 
    mainWindow = null; 
    }); 
}); 


//My html file 

<html> 
<head> 
<!--<script type="text/javascript" src = "index.js"/>--> 
<script type="text/javascript" src="index.js"></script> 
    <script type="text/javascript"> 
    alert(dps); --- not getting dps value here(/anywhere in html) 
</head> 
</html> 

回答

0

你的index.html中运行的代码在index.js一个不同的进程(通常被称为渲染过程)比你(whic h在主进程中运行)。此外,你的index.js文件是一个模块,因此,即使这两个文件是由同一个进程运行的,你也必须导出你的变量dps或者使其成为一个像global.dps这样的全局变量(然而,这是一个不好的做法!) 。

有几种方法可以在Main和Renderer进程之间共享日期; Electron为此提供了ipcMain,ipcRendererremote模块;您还可以使用URL编码参数将数据从Main传递到Renderer(但如果数据发生更改,这不会对您有所帮助);最后,您可以使用任何其他形式的IPC(例如,通过套接字发送消息,使用共享内存或共享文件等) - 但最好从Electron的ipcremote模块开始。

话虽如此,在你的情况下,consensus似乎不是使用数据库访问的主进程只是然后将信息传递给渲染器,而是直接从渲染器访问数据库;这样你根本不用担心IPC(至少在这种情况下)。

+0

感谢您的指导队友:) –