JSON偶尔未定义 - 我该如何检查?

时间:2016-05-04 12:38:28

标签: javascript php json ajax

因此,我试图访问的JSON对象有时不存在。

  

注意:未定义的索引:C:\ xampp \ htdocs \ example \ game.php中的电影

我在Steam API中使用此代码在game.php上找到它:

function returnGame () {
            $.ajax({
              url: "game.php",
              type: "post",
              dataType: 'json',
              success: function(data){
                  console.log(data);

                  $('#video').removeAttr('src');

                  ///// Game name /////
                  $('#gameName').html(data.gameName);
                  /////////////////////                   

                  ////// Append and load video /////
                  var videoSrc = data.gameTrailer;
                  var video_block = $('#video');
                  if (videoSrc !== null && videoSrc !== undefined) {
                        video_block.load();
                        document.querySelector('video').src = videoSrc;
                  } else {
                      $("#gameTrailer").find("#gameScreenshot").attr("src", data.gameScreenshot);
                  }
                  //////////////////////////////////
              },  
            }); 
        }

我使用AJAX在index.php上像这样戳game.php:

$GLOBALS['gameTrailer']

当电影为空时,AJAX功能不执行任何操作。视频不会更改为空白,并且电影标题不会更新为新内容。当电影没有被定义时,它的效果非常好。

我似乎无法将if(empty())视为未定义并重新迭代或替换为屏幕截图而非电影,但不是在game.php或index.php上。我尝试了if($GLOBALS['gameTrailer'] == NULL) {} {}和<?php if(isset($_POST)) { fetchGame(); } function fetchGame() { ////////// ID-picker ////////// $f_contents = file("steam.txt"); $url = $f_contents[mt_rand(0, count($f_contents) - 1)]; $answer = explode('/',$url); $gameID = $answer[4]; $trimmed = trim($gameID); ////////// Fetch game ////////// $json = file_get_contents('http://store.steampowered.com/api/appdetails?appids='.$trimmed); $game_json = json_decode($json, true); ////////// Store variables ////////// $GLOBALS['gameName'] = $game_json[$trimmed]['data']['name']; $GLOBALS['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max']; $GLOBALS['gameScreenshot'] = $game_json[$trimmed]['data']['screenshots'][0]['path_full']; $GLOBALS['gameImage'] = $game_json[$trimmed]['data']['header_image']; $GLOBALS['gameId'] = $trimmed; $GLOBALS['free'] = $game_json[$trimmed]['data']['is_free']; $GLOBALS['price'] = $game_json[$trimmed]['data']['price_overview']['final']; if(!isset($GLOBALS['price']) && ($GLOBALS['gameTrailer'])) { fetchGame(); } if ($GLOBALS['free'] === TRUE) { $GLOBALS['final_price'] = "Free"; } elseif($GLOBALS['free'] === FALSE || $GLOBALS['final_price'] != NULL) { $GLOBALS['final_price'] = $GLOBALS['price']; } else { $GLOBALS['final_price'] = "-"; } } ////////// Return to AJAX (index.php) ////////// echo json_encode(array( 'gameName' => $GLOBALS['gameName'], 'gameTrailer' => $GLOBALS['gameTrailer'], 'gameImage' => $GLOBALS['gameImage'], 'gameId' => $GLOBALS['gameId'], 'finalPrice' => $GLOBALS['final_price'], 'gameScreenshot' => $GLOBALS['gameScreenshot'] )) ; ?> 之类的内容,但即使game.php上的错误代码告诉我它未定义,它似乎表现得并非如此。

任何想法都将不胜感激。谢谢。

编辑:完整的game.php代码:

$GLOBALS['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];

它在第23行(import com.mongodb.DBObject import com.mongodb.casbah.MongoClient import com.mongodb.casbah.MongoClientURI import com.mongodb.util.JSON val jsonString = """{"card_id" : 75893645814809,"cust_id": 1008,"card_info": {"card_type" : "Travel Card","credit_limit": 126839},"card_dates" : [{"date":"1997-09-09" },{"date":"2007-09-07" }]}""" val dbObject: DBObject = JSON.parse(jsonString).asInstanceOf[DBObject] val mongo = MongoClient(MongoClientURI("mongodb://127.0.0.1:27017")) val buffer = new java.util.ArrayList[DBObject]() buffer.add(dbObject) mongo.getDB("yourDBName").getCollection("yourCollectionName").insert(buffer) buffer.clear() 作为未定义的索引)中断

1 个答案:

答案 0 :(得分:1)

好的,所以这里是对问题所作评论提供的代码的示例更新。

注意:

1)除非您知道自己在做什么以及为什么要使用它,否则不要使用$GLOBALS。在这种情况下,它似乎不是必需的。已更新至$game,因为它正在保存游戏详情。

2)您需要检查之前是否存在某些内容,然后尝试访问它。因此,您之前拥有的isset是无用的,因为您已经访问过不存在的数组项。删除了那张支票。

3)递归是好的,但同样,你需要知道你在做什么,以及你为什么要使用它。我怀疑这无论如何都是无意的,但是作为2的一部分被删除了。

4)你声明拥有一个视频(以及它的外观价格)是这个功能的要求,所以你应该事先检查一下。请注意,获取ID后的第一件事是查看是否有视频。为什么工作只是发现我们不能使用它?

5)如果没有视频,你想尝试不同的游戏,所以我们将循环中的检查和分配包起来,如果视频不在那里,我会continue。请注意,您可能希望将此限制为n次尝试,否则您可能最终会等待脚本查找具有视频的游戏的年龄,但这可供您自行决定。

<?php
if(isset($_POST)) {
    fetchGame();
}

function fetchGame() {
    $gameFound = false;

    while(!$gameFound) {
        ////////// ID-picker //////////
        $f_contents = file("steam.txt");
        $url = $f_contents[mt_rand(0, count($f_contents) - 1)];             
        $answer = explode('/',$url);
        $gameID = $answer[4];
        $trimmed = trim($gameID);

        ////////// Fetch game //////////
        $json =     file_get_contents('http://store.steampowered.com/api/appdetails?appids='.$trimmed);
        $game_json = json_decode($json, true);

        if(!isset($game_json[$trimmed]['data']['movies'][0]['webm']['max']) || !isset($game_json[$trimmed]['data']['price_overview']['final'])) {
            continue;
        }

        $gameFound = true;

        ////////// Store variables //////////
        $game['gameName'] = $game_json[$trimmed]['data']['name'];
        $game['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];
        $game['gameScreenshot'] = $game_json[$trimmed]['data']['screenshots'][0]['path_full'];
        $game['gameImage'] = $game_json[$trimmed]['data']['header_image'];
        $game['gameId'] = $trimmed;
        $game['free'] = $game_json[$trimmed]['data']['is_free'];
        $game['price'] = $game_json[$trimmed]['data']['price_overview']['final'];

        if ($game['free'] === TRUE) {
            $game['final_price'] = "Free";
        } elseif($game['free'] === FALSE || $game['final_price'] != NULL) {
            $game['final_price'] = $game['price'];
        } else {
            $game['final_price'] = "-";
        }
    }
}

////////// Return to AJAX (index.php) //////////
echo 
    json_encode(array(
        'gameName' => $game['gameName'],
        'gameTrailer' => $game['gameTrailer'],
        'gameImage' => $game['gameImage'],
        'gameId' => $game['gameId'],
        'finalPrice' => $game['final_price'],
        'gameScreenshot' => $game['gameScreenshot']
    ));
?>

请注意,此代码未经测试,但我希望能让您了解如何继续操作。