SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    eval a variable in javascript

    Hi all

    I didn't think this would be a problem at all, but basically, I need to pass a string into javascript, and then be able to use the variables that are in that string. Like so

    Code:
    var string = '{heading:"Im looking for"};';
    var values = eval(string);
    alert(values.heading);
    This results in "undefined", bleek!

    Does anyone know what i'm doing wrong here...
    Thanks in advance
    Bye

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,870
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The JSON library from http://www.json.org/js.html is the best way to do that.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Enthusiast archanapatel's Avatar
    Join Date
    Aug 2008
    Posts
    57
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Check it out with below code.

    It may work for you.

    var string = 'var heading="Im looking for"';
    eval(string);
    alert(headling);

  4. #4
    SitePoint Addict
    Join Date
    Jun 2006
    Location
    Durban, South Africa
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey awesome!
    Thanks for that site felgall
    They had an eval example right there.

    The corrected code looks like this

    Code:
    var string = '{heading:"Im looking for"}';
    var values = eval('(' + string + ')');
    alert(values.heading);
    I removed the ; from the string variable, and changed the eval argument.

    Thanks for your suggestion archanapatel but i'm going to stick with the json notation

    Cheers all


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •