将字符串转换为变量java

发布于 2024-10-22 03:48:19 字数 415 浏览 7 评论 0原文

我有一个字符串,就像

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

我需要这样的字符串视图,

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

以便将其附加到表单上进行选择

   for (var a in myOpts) 
   {
        var t = document.createElement("OPTION");
        t.value = a;
        t.appendChild(document.createTextNode(myOpts[a]));
        selectObj.appendChild(t);
    }

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) 
   {
        var t = document.createElement("OPTION");
        t.value = a;
        t.appendChild(document.createTextNode(myOpts[a]));
        selectObj.appendChild(t);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彻夜缠绵 2024-10-29 03:48:19

如果您json_decode您的字符串,您将获得一个具有 3 个自有属性的普通对象。然后,您可以使用 for..in 构造循环这些属性:

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
    }
}

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
    }
}
白昼 2024-10-29 03:48:19

然而,你的问题有点不清楚 - 我会尝试猜测你在说什么,涵盖所有情况并提供一点附加值;)

我假设你在 JSP 页面中有一个服务器端字符串,其值是

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

它看起来像什么

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

现在您想将其写入文档,以便稍后可以在客户端代码上for它。

从这个意义上说 - 您需要区分几种情况。

尽管当服务器将其写入响应文档时它是一个字符串 - 客户端代码可以通过不同的方式获取该值。在所有这些中,服务器必须以特定方式写入数据,以便客户端可以访问它,但是有效性规则不同。

写一个对象文字

实际上 - 我认为这就是你想要做的。
客户端代码不会将其作为字符串获取,而是将其作为对象文字获取。

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

此选择的限制是来自服务器代码的任何内容(<%%> 内)以及来自标记的任何内容(<%%> 之外) code>) 必须作为有效的 JavaScript 对象文字一起工作。
有很多事情可能会破坏这个对象字面量的合法性——比如损坏的字符串、缺少逗号、缺少冒号等等。尽管这是推荐的方式 - 你必须知道你在做什么,我建议你扩大这些知识,你的例子是一个很好的开始。

在您的示例中 - 这会呈现为有效的 JavaScript 对象文字,并且问题不存在。

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

这是一个完全合法的对象文字,可以在 for 中使用 - 就像您所做的那样。

您的示例可能是您案例的简化,并且您使用的字符串可能会破坏您的执行。以下是如何处理从服务器到客户端代码的字符串:

编写 JavaString 字符串

这种情况下的限制 - 是 data 字符串中可能破坏 JavaSctipt stringbngs 的任何字符 - 必须对于 javascript 进行转义。

在这里,我只处理整个 data 值,但是请记住,您可能希望对放入此 data 中的每个值执行相同的操作。

下面是最简单的实现,解释了如何转义 JavaScript 的 Java 字符串:

<%!
    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>

这部分将确保您将所有数据从服务器获取到客户端,并且客户端可以访问这些数据。从那里开始 - 这是您自己的传输数据协议并在客户端上解析它的问题。

但是,并不总是建议这样做:如果您提供的所有内容都可以表述为对象文字 - 那就更好了 - 因为浏览器会在编译的代码中为您处理解析,并为脚本代码提供现成的对象。

除非您想解析自己的字符串协议,否则看起来 - 它会得到与以下内容相同的结果,那么为什么还要麻烦呢?更好地safeJs您的价值观。

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

将字符串写入 TextArea 的内容

这是在服务器和 HTML 客户端之间传递字符串的最可靠方法 - 因为唯一可能中断的情况是数据字符串包含以下结束标记文本区域。

文本区域不受换行符影响,不受引号(单引号和双引号)影响,它唯一的弱点是它自己的结束标记。

请注意,将“”替换为“

为文本区域分配一个 ID 并将其放入 style="display:none" 中可确保它不会干扰 UI,但仍可访问。

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

在 Select 中构建选项

createElement 的 DHTML 技巧很有效,但是我很少使用它,因为它很麻烦,而且性能很低。
但是 - 如果您成功地正确编写了对象文字 - 它应该可以工作。

注入 HTML

与创建选择并尝试填充它相比,将其完全注入 DOM 更快、更可靠。

为此,我使用以下实用程序:

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;
}

(function(){})() 中的换行创建一个匿名函数并立即执行它 - 这确保没有变量被宣布为这项工作将污染全球范围。

第一种方式 - 使用 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>

第二种方式 - 使用innerHTML
您可以执行相同的操作,而不是 document.write - 使用容器标记来标记选择的位置,甚至在 DOM 完成加载后将其注入那里。

它与第一种方式相同,但有一个区别:改为 document.write(HTML); -
将一个容器,例如 放在您想要选择的位置,然后使用
document.getElementById("oSelectPlace").innerHTML = HMTL;

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("</","</")%></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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文