使用Javascript以json格式检索Flickr图像

时间:2012-04-05 12:46:06

标签: javascript html json

我一直在努力寻找flickr一段时间。最初我用PHP检索XML文件并将其转换为simpleXML但我无法使用Javascript访问信息来构建图像链接。很沮丧!

所以我决定通过放弃PHP并使用json交换到javascript获取链接来简化它。

  1. 我在将文本输入到文本框中以填充flickr请求时遇到问题。

  2. 当我在此链接中手动使用文本术语时,它会检索没有图像的图像框。当我点击图像框时,指向Flickr的链接可以正常工作。

  3. 我做错了什么?!

    任何帮助都会非常感激,因为我现在尝试了3-4种不同的方式,但仍觉得我无处可去!

    由于 麦克

        <script type = "text/javascript">
            function jsonFlickrApi(rsp){ 
                window.rsp = rsp;
    
                var display = "";
    
                // loop through the objects to build the images from the json response
    
                for(var i=0; i<rsp.photos.photo.length; i++){
                    photo = rsp.photos.photo[i];
    
                // use the various elements of the json object to build the link
    
                    details_url = "http://farm" +photo.farm+ "static.flickr.com/" +photo.server+ "/" +photo.id+ "_" +photo.secret+ "_" + "t.jpg"; <!-- get
                    owner_url = "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id;
                    display += '<a href="' + owner_url + '">' + '<img alt="'+photo.title + '"src="' + details_url + '"/>' + '</a>';
                }
                // display the images
                document.writeln(display);
    
            }
    
        </script>
    

        

    这是一个flickr搜索

    <!-- the form is supposed to take a request from the user -->
    
    <form id="flickr_form">
        <input type="text" name="search" id="search"/>
        <input type="submit" value="Search"/>
    
    </form>
    
    <script src = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=0a109e625227a913ef57ac207f1af24f&text="+document.getElementById("search").value+"&per_page=10&format=json">
    
       </script>
    

1 个答案:

答案 0 :(得分:0)

1)脚本的src行中的JS命令不会被执行。我可以建议两种方法将搜索框值放入URL:

  • 既然你提到过PHP,为什么不简单地使用表单来正常使用GET(method =“GET”)提交并从中构造src URL?您可以将"+document.getElementById("search").value+"替换为<?=urlencode($_GET['search'])?>,这应该可以起作用。该页面将比通过JS加载一次,但这可能是解决该问题的最快方法。它仅用于测试目的,在实际的网站上,这只是一种糟糕的风格。
  • 或者,您可以编写在提交表单时要执行的功能,例如:与<form onsubmit='load_flickr(this);return false;'>类似,您应该能够在this.search.value内访问load_flickr,从中构建flickr请求网址,然后加载脚本。

2)details_url行末尾的<!-- get是什么?我假设这里的复制+粘贴只是一个错误,实际上并不在你自己的代码中。

3)可能是最重要的错误:您在图片网址(farmX.static.flickr.com而不是farmXstatic.flickr.com)中的“静态”之前错过了一个完整的停止位置: - )