如何使用Nashorn将Javascript对象从Java传递到Javascript

时间:2017-05-12 06:34:21

标签: javascript java nashorn scriptengine

我有一个String形式的JavaScript对象(实际上来自数据库)我需要使用Nashorn(Java 8)传递给Javascript函数。引擎将在javascript中作为字符串传递的参数视为对象。我希望它将它标识为Javascript对象。

以下是代码段:

<link href="http://code.ionicframework.com/0.9.23/css/ionic.css" rel="stylesheet">
    <script src="http://code.ionicframework.com/0.9.23/js/ionic.js"></script>
    <script src="http://code.ionicframework.com/0.9.23/js/angular/angular.js"></script>
    <script src="http://code.ionicframework.com/0.9.23/js/angular/angular-animate.min.js"></script>
    <script src="http://code.ionicframework.com/0.9.23/js/angular/angular-sanitize.min.js"></script>
    <script src="http://code.ionicframework.com/0.9.23/js/angular-ui/angular-ui-router.min.js"></script>
    <script src="http://code.ionicframework.com/0.9.23/js/ionic-angular.js"></script>
    
    <div ng-app="myApp">
    <div ng-controller="Ctrl as myCtrl">
<ion-view title="Single Projector Room" id="page9">

<ion-nav-buttons side="left">
    <button class="button back-button buttons button-clear header-item" ng-click="goBack()">
      <i class="icon ion-ios-arrow-back"> Back</i> 
    </button>
  </ion-nav-buttons>

  <ion-content padding="true" style="background: url(img/EDD79InSMCeYeMOSchjm_remote.jpg) no-repeat center;background-size:cover;" class="has-header">

  


  <div class="row">
    <div class="col col-offset-5 col-30 text-center">
      <button class="button button-large icon-right ion-power"ng-class="{active: myCtrl.onactive}" ng-click="myCtrl.changeColorIcons('on')">On</button>
    </div>
    
  </div>

  <div class="row">
    <div class="col col-offset-5 col-30 text-center">
      <button class="button button-large icon-right ion-android-cancel" ng-class="{active: myCtrl.offactive}" ng-click="myCtrl.changeColorIcons('off')">Off</button>
    </div>
   
  </div>

 

  </ion-content>

</ion-view>
    </div> 
</div>

我得到的错误是:
   javax.script.ScriptException:TypeError:无法读取属性&#34; value&#34;来自第1行的未定义

2 个答案:

答案 0 :(得分:1)

您可以先将dataModel字符串转换为JSON - 在函数本身或其他地方,然后传递它。

示例:

String dataModel = ...;
// convert the string as a JSON object
engine.put("dataModel", dataModel);
JSObject obj = (JSObject)engine.eval("JSON.parse(dataModel)");
...
// dataModel is a script object - as it is a result of JSON.parse
// pass it as parameter for genData
inv.invokeFunction("genData", obj);

答案 1 :(得分:1)

如果您的dataModel是一个简单的Java Map,那么您可以直接将其作为参数传递给invokeFunction。对于更高级的用途,您的参数应实现Bindings接口。

为了使这更容易,我写了一个名为json的库:

Example

    Json j = new Json("a", 5);
    Double result = (Double) eng.eval("a+1", j);