0

Thanks for taking a look : )

I know that I can add multiple objects at once in a javascript array like this:

<script>

    var myCarsArray = ["Saab","Volvo","BMW"];

    alert("The second element in my array = "+myCarsArray[1]);

</script>

This alerts 'The second element in my array = Volvo'.

I want to simply store the array values in the database as a string - so in the database would be a field called 'My_Cars_Array_Database_String_Value' and I will place my array values there the exact same way I would place them in the array with javascript - so the string would look like this:

"Saab","Volvo","BMW"

Now I get the string value using MySQL and echo the value using PHP, like this

<script>

    var myCarsArray = [<?php echo $My_Cars_Array_Database_String_Value; ?>];

    alert("The second element in my array = "+myCarsArray[1]);

</script>

This alerts 'The second element in my array = S' !? It's treating the whole string as an array.

So the only way I could get this to work was to use 'eval' this way :

<script>

   var myCarsArray = eval("["+<?php echo $My_Cars_Array_Database_String_Value; ?>+"]");

   alert("The second element in my array = "+myCarsArray[1]);

</script>

This alerts correctly 'The second element in my array = Volvo'.


My question is: How do I save the string to the database so that I can just insert it into the javascript array as is, using:

myCarsArray = [<?php echo $My_Cars_Array_Database_String_Value; ?>];

?

WITHOUT using a loop of any kind - I understand how to achieve this with a loop - I don't want to use a loop. Or is the 'eval' method the only way?


Clarification:

The question on this post is how to save javascript usable array values - as a string to MySQL - that can later be easily inserted into an array via -

myCarsArray = [<?php echo $My_Cars_Array_Database_String_Value; ?>]; 

method.

AND Can this be done without using loops or the 'eval' statement?

Thanks in advance - I look forward to your replies.

Regards, Ken

4

3 回答 3

0

你不想用循环使事情复杂化吗?它们是基本且有效的流量控制工具,您已经通过尝试使用 eval 技巧使自己变得多么复杂?

eval 是邪恶的,避免它。您正在尝试从服务器评估 JavaScript,但您不知道它会做什么。

明确说明您要做什么,这不仅会使将来的维护更容易,而且如果其他人继承了您的工作,他们就不会想追捕您并对您做坏事以使他们的工作成为噩梦.

于 2012-09-04T23:01:01.373 回答
0

我的 PHP 语法有点生疏,但你应该可以这样说:

<php
  <script>
  echo "var array = " . json_encode($My_Cars_Array_Database_String_Value) . ";";
  </script>
?>
于 2012-09-04T22:55:48.047 回答
0
MultiDimeArray = { SomeOtherValues:"SomeValue", 
                   myCarsArray:"<?php echo $My_Cars_Array_Database_String_Value; ?>" 
                 };

假设它应该是

MultiDimeArray = { SomeOtherValues:"SomeValue", 
                   myCarsArray:[<?php echo $My_Cars_Array_Database_String_Value; ?>] 
                 };

在您的输出中: myCarsArray: " 'Saab','Volvo",'BMW' "而不是 myCarsArray: [ 'Saab','Volvo",'BMW' ]

于 2012-09-04T22:57:07.383 回答