简体   繁体   中英

How to convert javascript array to scala List object

I have inherited some code that uses the Play! framework which has scala.html files that have javascript in them. Play! and scala are all new to me.

One of the javascript functions does a post and gets back a JSON object. It then loops through the JSON object and creates an array.

var myArray = [];

function createArray(){
   $.post('/createArray', $('#arrayForm').serialize()).done(function( data ) {
       var obj1 = JSON.parse(data);
         $.each(obj1, function(idx, obj) {
             myArray.push(obj.name);
        });   
   });
   return true;
} 

It then uses this array (of strings) to create a text input field that does autocomplete using the data in the array.

I want/need to convert this text input to a select dropdown using the Play! @select but the options arg for @select wants a List object (or Map or Seq - just figured List would be easier since I already have an array of strings).

If I manually create the List object, it works fine.

@select(pForm("equipName"), options(scala.collection.immutable.List("Yes","No")))

The problem is I cannot figure out how to convert the myArray array to a List object which I can then pass to the @select options.

I have found a lot of posts that talk about converting a scala List to an array but can't find a way to go the other way. I am hoping it is an easy thing that I can't seem to figure out.

Thanks in advance for the help.

You can not do that. And more precisely - you do not want to do that.

So basically your play application run on server. In your Play application all those .scala html files are compiled to generate some functions.

Now, when a play application receives a request from a client browser, it gets mapped to some controller by by router. The controller does some processing and finally take one of these above functions ( lets say for index.scala.html we get views.html.index ) and call this function with some parameters.

These functions returns some text which is then sent to the client's browser as HTTP response with response header Content-Type:text/html; charset=utf-8 Content-Type:text/html; charset=utf-8 which tells the browser to treat this text as html .

Now, the browser renders the html which has embedded JavaScript and hence runs the JavaScript. So... basically your JavaScrpt code does not exist on server... for play all of it is just text.

Both of these Scala code and JavaScript code are executed at very different times, at different computers and in different environments hence you can not do whatever you are saying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM