0

OK let's say I have this:

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">
Hello<br />
</div>
<script>
$.getJSON("main.txt",
  function(data) {
    var getTitle = title;    
    $.each(data.getTitle, function(i,getTitle){
       $("#images").append(getTitle);
    });
  });</script>
</body>
</html>

it doesn't work because of var getTitle = title. I know that. But if I take out the var and replace getTitle with title which is INSIDE the JSON file.. it WILL work. But I don't want to edit three pieces of title for each code so I just make a variable so I can edit all three at once... but it doesn't work...

3
  • 1
    I dont't understand what do you try to do. what is title - is it defined somewhere? Commented Oct 15, 2011 at 19:43
  • @Guard, Its a typo, he meant var getTitle = "title"; The point being if the JSON changes, that he only has to change the value of getTitle.. I agree that it wasn't massively clear though. Commented Oct 15, 2011 at 19:59
  • data.title is a string. Why are you using $.each()? Commented Oct 15, 2011 at 20:15

2 Answers 2

2

Instead of accessing the object as data.getTitle, try using [].

var getTitle = "title";
$.each(data[getTitle], function(........)

This would solve the problem.

Sign up to request clarification or add additional context in comments.

Comments

1

I just make a variable so I can edit all three at once

That doesn't make any sense. The name of the variable doesn't matter at all. For what you're doing, this works just as well:

$.getJSON('main.txt', function(data) {
    $.each(data.title, function(i, anyVariableNameILikeGoesHere) {
        $('#images').append(anyVariableNameILikeGoesHere);
    });
});

However, jQuery actually provides a more concise way of writing this:

$.getJSON('main.txt', function(data) {
    $.each(data.title, function() {
        $('#images').append(this);
    });
});

Aside from that though, why are you iterating over data.title? Looking at your json, it's a single string! This is a much better way to write it:

$.getJSON('main.txt', function(data) {
    $('#images').append(data.title);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.