Javascript eval() not working with passed string - Stack Overflow

My code snippet:function receive(mag){var text = eval(mag);alert(text);}receive('["magnolia

My code snippet:

function receive(mag)
{
    var text = eval(mag);
    alert(text);
}

receive('["magnolia,", ["Magnolia (Flower)"], [], [], [], [], [], [[3, 19019, "INV_MAG_39 ", 5]]]');

When I pass the string in the example (shown above), the eval(mag) doesn't work. But if I do it directly like this:

function receive(mag)
{
    var text = eval('["magnolia,", ["Magnolia (Flower)"], [], [], [], [], [], [[3, 19019, "INV_MAG_39 ", 5]]]');
    alert(text);
}

It does work. Does anyone have an idea whats wrong / how can I get it working with passed variable?

My code snippet:

function receive(mag)
{
    var text = eval(mag);
    alert(text);
}

receive('["magnolia,", ["Magnolia (Flower)"], [], [], [], [], [], [[3, 19019, "INV_MAG_39 ", 5]]]');

When I pass the string in the example (shown above), the eval(mag) doesn't work. But if I do it directly like this:

function receive(mag)
{
    var text = eval('["magnolia,", ["Magnolia (Flower)"], [], [], [], [], [], [[3, 19019, "INV_MAG_39 ", 5]]]');
    alert(text);
}

It does work. Does anyone have an idea whats wrong / how can I get it working with passed variable?

Share Improve this question edited Sep 11, 2012 at 23:03 BadFeelingAboutThis 14.4k2 gold badges34 silver badges40 bronze badges asked Sep 11, 2012 at 22:41 xtraxtra 691 gold badge3 silver badges9 bronze badges 8
  • 3 What does "won't work" mean? What actually happens with the first version? (Do you get any errors in the console?) – nnnnnn Commented Sep 11, 2012 at 22:43
  • 1 No really, stop using eval(). – SeanCannon Commented Sep 11, 2012 at 22:46
  • 5 Try using JSON.parse instead of eval. – gen_Eric Commented Sep 11, 2012 at 22:46
  • 1 Because eval will execute anything inside the string, and since it only makes sense to eval external data, it is potentially very dangerous. – Aesthete Commented Sep 11, 2012 at 22:49
  • 2 Your code works here: jsfiddle/HvrzK – nnnnnn Commented Sep 11, 2012 at 22:49
 |  Show 3 more ments

1 Answer 1

Reset to default 4

I think you're missing the parenthesis:

eval('(' + mag + ')')

But why not use JSON.parse??

var text = JSON.parse(mag);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744317822a4568268.html

相关推荐

  • Javascript eval() not working with passed string - Stack Overflow

    My code snippet:function receive(mag){var text = eval(mag);alert(text);}receive('["magnolia

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信