سؤال

I'm using the current json structure of this:

jsonp = {"game":[
              {"id":"1","gameImage":"qqq.jpg"}
              ],
        "game":[
              {"id":"2","gameImage":"hhh.jpg"}
              ]
       }

I'm trying to just get back all the gameImage values. I tried the following but it just won't work. Any ideas?

<html>
    <head></head>
<body>

    <script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
    <script type="text/javascript" language="javascript" src="gameData.json"></script>
    <script>
    $(document).ready(function() {


  var obj = $.parseJSON(jsonp);
      $.each(obj, function() {
          alert(this['gameImage']);
      });

});
        </script>



    </body>
    </html>
هل كانت مفيدة؟

المحلول

Assuming the first code you show is in the file (incorrectly) named "gameData.json", what you're trying to parse isn't JSON (or JSONP), it's plain JavaScript.

So don't parse it.

Change

var obj = $.parseJSON(jsonp);

to

var obj = jsonp;

Notes :

  • JSON is a text based data interchange format. Your confusion might come from the many young developers using non-sensical expressions like "JSON object"...
  • You should avoid naming jsonp a variable holding a plain JavaScript object.

If you prefer to load a JSON file instead of executing a JavaScript file, then

  1. remove the "jsonp = part to make it a real JSON file
  2. remove the script element (as it's not JavaScript anymore)
  3. load the JSON file using ajax

Here's how the JavaScript would be like :

$(document).ready(function() {
   $.getJSON("gameData.json", function(obj){
      $.each(obj, function() {
          alert(this['gameImage']);
      });
   });
});

or, if you can afford not supporting IE8 :

$(document).ready(function() {
   $.getJSON("gameData.json", function(arr){
      arr.forEach(function(item){
          console.log(item.gameImage); // yes, prefer the console over alert
      });
   });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top