开发者

convert string to a variable java

开发者 https://www.devze.com 2023-02-16 17:49 出处:网络
i have i string like 5: \"White\", 6: \"Yellow\", 7: \"Pink\" i need that string view like this s={5: \"White\", 6: \"Yellow\", 7: \"Pink\"};

i have i string like

5: "White", 6: "Yellow", 7: "Pink"

i need that string view like this

s={5: "White", 6: "Yellow", 7: "Pink"};

for attach it to select on form

   for (var a in myOpts) 
开发者_C百科   {
        var t = document.createElement("OPTION");
        t.value = a;
        t.appendChild(document.createTextNode(myOpts[a]));
        selectObj.appendChild(t);
    }


If you json_decode your string s, you will get a plain object with 3 owned properties. Then you can loop on those properties with the for..in construct:

var myOpts, s='{5: "White", 6: "Yellow", 7: "Pink"}';
eval('myOpts='+s); // or better, a json parser
for(var a in myOpts) {
    if(myOpts.hasOwnProperty(a)) {
       // your dom code here
    }
}


Your question is a little unclear, however - I'll try to guess what you're saying, cover all cases and give a little added value ;)

I assume that you have a server-side string in a JSP page, who's value is

5: "White", 6: "Yellow", 7: "Pink"

What makes it look like

 <%
 String data = "5: \"White\", 6: \"Yellow\", 7: \"Pink\"";
 %>

And now you want to write it to to the document, so you can for it later on on client-side code.

In that sense - you need to distinguish between few cases.

Although when the server writes it into the response document it is a string - the client code can get this value in different ways. In all of them - the server must write the data in a specific way so that the client can access it, however, the validity rules are different.

Write an object literal

Actually - I think that that's what you're trying to do. The client code does not get it as a string - but as an object literal.

<script>
var sObjData = {<%= safeJs(data) %>};
</script>

The limits of this choice is that whatever comes from the server code (within the <%%>) and whatever comes from the markup (outside the <%%>) must work together as a valid JavaScript object literal. There are many things that can break legality of this Object literal - like broken strings, missing commas, missing colons, and so on. Although this is the recommended way - you have to know what you're doing, and I advise you to gap up this knowledge, and your example is a good start.

In your example - this renders to a valid JavaScript Object-Literal, and the problem is not there.

<script>
var sObjData = {5: "White", 6: "Yellow", 7: "Pink"};
</script>

This is a perfectly legal object literal that can be used in for - just the way you do.

It could be that your example is simplification of your case, and the strings that you use may break your execution. Here's how to handle strings from server to client-code:

Write a JavaString string

The limits in this case - is that any character in data string that might break JavaSctipt strinbngs - must be escaped for javascript.

Here I just treat the whole data value, however - bear in mind that you might want to do the same for every values that you put inside this data.

Here's the simplest implementation that explains that's to escape a Java string for JavaScript:

<%!
    String safeJs(String data){
        return data.replace("\"","\\\"") //why three? two emit a sigle \ and the third escape the "
                   .replace("'","\\'")
                   .replace("\n","\\n")  //why two? you're not escaping n, your're emitting \ and n
                   .replace("\r","\\r"); //    that will render as escaping for the client code
    }
%>
<script>
var sObjData = '<%= safeJs(data) %>';
<script>

This part will assure that you get all the data from the server to the client, and that it will be accessible to the client. From there - it's a matter of your own protocol of delivering data and parsing it on the client.

However, this is not always recommended: If all you're delivering can be formulated as an Object Literal - it is much better - because the Browser handles the parsing for you in a complied code, and gives the scripting code a ready-made object.

Unless you want to parse your own string-protocol, seemingly - its gets the same result to the following, so why bother? better to safeJs your values.

<script>
var sObjData = '<%= safeJs(data) %>';
var oObjData = eval("{" + oObjData + "}");
<script>

Write the string to a content of a TextArea

This is the most robust way of passing strings between server and an HTML client - because the only thing that can break - is if the data string contains a closing tag of TextArea.

A text area is immune to line-breaks, it is immute to quotation marks (single and double), it's sole weakness is it's own closing tag.

Note that replacing the "" with "<textarea>" and "" with "<textarea>".

Assigning an ID to the text area and putting it in style="display:none" assures that it will not bother the UI, and yet be accessible.

<textarea style="display:none" id="txtData"><%=data.replace("</","&lt;/")%></textarea>
<script>
    var s = document.getElementById("txtData");
</script>

building options in a Select

The DHTML tricks of createElement works, however, I rarely use it, because it's cumbersome, and very low on performance. However - if you managed to write your Object Literal properly - it should work.

injecting HTML

Instead of creating a select and trying to populate it - it is faster and more reliable to inject it completely into the DOM.

I use the following utility for that:

function getStringBuffer(){
    var bfr = [];
     bfr.add = function() {
        for(var i=0;i<arguments.length;i++) {
           this[this.length] = arguments[i];
        }
     }
     bfr.toString = function() { return this.join("") }
     return bfr;
}

The wrap in (function(){ and })() creates an anonymous function and executes it instantly - that assures that no variables that are declared for this work will pollute the global scope.

first way - using document.write:

<script>
(function(){
  var HTML = getStringBuffer();
  var k;

  HTML.add("<select id='selectObj'>");
  for (k in myOpts)  {
      HTML.add("<option value='", k, "'>", myOpts[k],"</option>");
  }
  HTML[HTML.length] = "</select>";

  document.write(HTML); //note the overriden toString method that will be called here
})();
</script>

Second way - using innerHTML You can do the same and instead document.write - use a container tag to mark the place of the select, and inject it there even after the DOM has finished loading.

it's the same as the first way, in one difference: Instead document.write(HTML); - put a container, say <span id="oSelectPlace"></span> where you want the select to be, and then use document.getElementById("oSelectPlace").innerHTML = HMTL;

0

精彩评论

暂无评论...
验证码 换一张
取 消