admin管理员组

文章数量:1319002

$.getJSON(
    "test.php",
    function(data){
        ... code should be here?
    }
)

data contains this code:

{
    "name": "Mary",
    "surname": "Carey"
}

I want to create these variables:

theName = name from json;
theSurname = surname from json;

What is a true syntax for this task?

Thanks.

$.getJSON(
    "test.php",
    function(data){
        ... code should be here?
    }
)

data contains this code:

{
    "name": "Mary",
    "surname": "Carey"
}

I want to create these variables:

theName = name from json;
theSurname = surname from json;

What is a true syntax for this task?

Thanks.

Share Improve this question edited Feb 2, 2011 at 17:20 jball 25k9 gold badges72 silver badges92 bronze badges asked Feb 2, 2011 at 17:15 JamesJames 43.7k54 gold badges137 silver badges163 bronze badges 3
  • 2 theName = data.name; theSurname = data.surname; – jball Commented Feb 2, 2011 at 17:16
  • 1 See the example in the manual: api.jquery./jQuery.getJSON – Pekka Commented Feb 2, 2011 at 17:17
  • possible duplicate of How do I access the value of this JavaScript object? – jball Commented Feb 2, 2011 at 17:25
Add a ment  | 

3 Answers 3

Reset to default 3

Dot notation:

theName = data.name;
theSurname = data.surname;

or square-bracket notation:

theName = data['name'];
theSurname = data['surname'];

You could do:

theName = data.name
theSurname = data.surname

… but it is probably better to keep them nicely wrapped up in data and just use that.

The "data" should be a Javascript Object. If that is truly the data, you should be able to access it with data['name'] and data['surname'].

'dot' syntax should also work. (i.e. data.name and data.surname)

本文标签: javascriptjQuery json decodeStack Overflow