【问题标题】:Getting a random value in ajax GET url在ajax GET url中获取随机值
【发布时间】:2014-05-15 00:44:59
【问题描述】:

编辑:我已经设法解决了上述问题,但是每次加载时 max_id 都会返回相同的值,因此会继续加载相同的 20 张照片。

我正在尝试从主题标签中提取 Instagram 照片,然后在您滚动到页面底部时使用 ajax 提要调用下一组照片。问题是,我的 ajax 脚本从某个地方获取一个随机值并将其放在我的 GET url 的末尾,这使得该 URL 无用。

我已经检查了我所有的代码一整天都找不到错误的地方。

index.php

jQuery(document).ready(function(){

$('#imore').bind('click', function(){
    var tag   = $(this).data('tag'),
        maxid = $(this).data('maxid'),
        $c = $('div#instphotos'),
        $newItems = '';

    $.ajax({
      type: 'GET',
      url: 'ajax.php',
      data: {
        tag: tag,
        max_id: maxid
      },
      dataType: 'json',
      success: function(data) {
        // Output data

        $.each(data.images, function(i, src) {

            var $newItems = $('<div class="mblock"><span class="number">1</span><div class=""><a href="'+data.images[i].src+'?loadtype=iframe" class="imagebox fancybox.iframe" ititle="<div class=&quot;posttitle&quot;>@</div><div style=&quot;float:right;margin-right:15px;&quot;></div><div class=&quot;clear&quot;></div>"><img src="'+data.images[i].thumb+'"></div>').css('opacity', 0); 
            $c.isotope( 'insert', $newItems ).fadeTo('fast', 1); 

        });
        $('#imore').data('maxid', data.next_id);

      }

    });
});
});

<?php
/** Instagram PHP API */
require_once 'instagram.class.php';

// Initialize class with client_id
// Register at http://instagram.com/developer/ and replace client_id with your own
$instagram = new Instagram('19a4efd22cc1442d97057bd1083e3385');

// Get latest photos according to geolocation for Växjö
// $geo = $instagram->searchMedia(56.8770413, 14.8092744);

$tag = 'subarulove';

// Get recently tagged media
//$media = $instagram->getTagMedia($tag);

$media = $instagram->getTagMedia('breakfast',$auth=false,array('max_tag_id'=>$maxID));

// Display first results in a <ul>
echo '<div id="instphotos">';

$i = 1;
foreach ($media->data as $data) {
    echo '  <div class="photo mblock"><span class="number">'.$i.'</span><div class=""><a href="'.$data->images->standard_resolution->url.'?loadtype=iframe" class="imagebox fancybox.iframe" ititle="<div class=&quot;posttitle&quot;>@'.$data->user->username.'</div><div style=&quot;float:right;margin-right:15px;&quot;></div><div class=&quot;clear&quot;></div>">'."\n";
    echo '    <span class="roll"></span>'."\n";
    echo '    <img src="'.$data->images->low_resolution->url.'"></a></div></div>'."\n";
$i++;
}
echo '</div>';

echo '<div id="imore" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'"><a href="#">Load more ...</a></div>';
?>

ajax.php

 require_once 'instagram.class.php';

  // Initialize class for public requests
  $instagram = new Instagram('19a4efd22cc1442d97057bd1083e3385');

  // Receive AJAX request and create call object
  $tag = !empty($_GET['tag']) ? $_GET['tag']: null;
  $maxID = !empty($_GET['maxid']) ? $_GET['maxid']: null;
  $clientID = $instagram->getApiKey();

  $call = new stdClass;
  $call->pagination->next_max_id = $maxID;
  $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

  // Receive new data
  $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

  // Collect everything for json output
  $images = array();
  if($media){
    foreach ($media->data as $data) {
      $src = $data->images->standard_resolution->url;  
      $thumb = $data->images->low_resolution->url;  
      $url = $data->link;

      $images = array();
       foreach ($media->data as $data) {
        $images[] = array(
          $data->images->standard_resolution->url,
          $data->images->low_resolution->url,
          $data->link,
          $data->likes->count
        );
      }
    }

    echo json_encode(array(
      'next_id' => $media->pagination->next_max_id,
      'images' => $images
    ));
  }
?>

在控制台中,只要它运行 ajax 请求,它就会返回: GET http://url.com/ajax.php?tag=breakfast&max_id=1400131855765479&_=1400114008166 500(内部服务器错误)

粗体部分是插入到 URL 中的随机值。

【问题讨论】:

  • 来自 AJAX 中的 cache: false,,它是阻止浏览器发送缓存响应的当前时间戳,但它不应该导致 500 错误。检查您的错误日志
  • 我已经删除了缓存行,但它仍然给我同样的东西。我确实有以下行的错误日志:[15-May-2014 00:57:06 UTC] PHP 警告:从第 17 行的 /home/public_html/ajax.php 中的空值创建默认对象 [2014 年 5 月 15 日00:57:06 UTC] PHP 致命错误:在第 37 行的 /home/public_html/ajax.php 中调用未定义的方法 stdClass::getId()
  • 第 17 行是:$call->pagination->next_max_id = $maxID;我发现了第 37 行的问题。
  • 是的,我正要写一个答案,你创建了一个 std 对象 $call = new stdClass; 但是然后用 $call-&gt;pagination-&gt;next_max_id 为一个未定义的对象赋值,你也应该将分页分配为一个 std 类, 或使用数组,$call 无处使用,但其中几行,所以保持简单。
  • 您还需要检查您的 $_GET 是否设置为 $tag = !empty($_GET['tag']) ? $_GET['tag']: null; 并在为空时执行某些操作。仅仅因为您的脚本发送了请求并不意味着有人不会测试它的弱点或将其用作自己的 API。它发生了

标签: php jquery ajax json instagram


【解决方案1】:

要添加分页,你需要调用分页方法,然后后续请求使用next_id,也修复了Strict Standards: Creating default object from empty value... error的问题

经过整理的示例

<?php 
require_once 'instagram.class.php';

// Initialize class for public requests
$instagram = new Instagram('19a4efd22cc1442d97057bd1083e3385');

// Receive AJAX request and create call object
$tag   = !empty($_GET['tag'])     ? $_GET['tag']     : 'subarulove';
$maxID = !empty($_GET['next_id']) ? $_GET['next_id'] : 0;
$clientID = $instagram->getApiKey();

$call = new stdClass;
$call->pagination = new stdClass();
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

// Receive new data
$media = $instagram->pagination($call, 8); //max to load

// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
    $images[] = array(
        'url'   => $data->images->standard_resolution->url,
        'thumb' => $data->images->low_resolution->url,
        'url'   => $data->link,
        'likes' => $data->likes->count 
    );
}


if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    header('Content-Type: application/json');
    exit(json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images' => $images
    )));
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Instagram pagination example using jQuery AJAX</title>

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){

    $('#imore').bind('click', function(){

        var request = $.ajax({
            url: "./index.php",
            type: "GET",
            data: { tag: $(this).data('tag'), next_id: $(this).data('next_id') },
            dataType: "json"
        });
        request.done(function( data ) {
            $.each(data.images, function(i, src) {
                $('<img src="'+data.images[i].thumb+'">').appendTo("div#instphotos");
            });

            $('#imore').data('next_id', data.next_id);
        });
        request.fail(function( jqXHR, textStatus ) {
            alert( "Request failed: " + textStatus );
        });

    });

});
</script>
</head>
<body>

<div id="instphotos">
<?php 
foreach ($images as $image){
    echo '<img src="'.$image['thumb'].'">';
}
?>
</div>
<div id="imore" data-next_id="<?php echo $media->pagination->next_max_id; ?>" data-tag="subarulove">
    <a href="Javascript:void(0);">Load more ...</a>
</div>

</body>
</html>

【讨论】:

  • sidenote 您可能还想缓存 API 调用的结果,或者您立即用完每日配额 :)
  • 什么会导致request.fail?
  • a 404,json 解析错误,基本上如果服务器返回的东西不是 200 和有效的 json,那么错误是什么?该示例是复制和粘贴,在您知道它在做什么之前,不要尝试将其集成到您当前的代码中,因为您的 php 有一些错误。还要检查示例中的 ajax 的 url 及其 index.php。
  • 我刚刚创建了一个全新的索引文件,复制并粘贴了您的代码,我收到了解析错误警报。 “请求失败:解析器错误”
  • 再次检查您的错误日志,返回的 json 应该没有任何问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2011-10-13
  • 2012-07-13
  • 2015-10-12
  • 2020-10-02
  • 1970-01-01
  • 2012-04-21
相关资源
最近更新 更多