如何通过AJAX获取API请求响应

时间:2015-01-21 17:34:23

标签: javascript php jquery ajax flickr

我正在尝试通过Ajax在我的应用程序中获取Flickr的API响应。我正在使用Laravel。我有一个特定的Route和一个函数来进行API调用。

//Route.php
Route::post('/getlocation/{latitude}/{longitude}', ['as'=>'get-location', 'uses'=>'FormController@getLocationImage']);

和功能

//getLocationImage()

//GET THE IMAGES BASED ON THE LOCATION FROM FLICKR.
            $api_key = 'my_api_key_is_here';
            $tag = 'night,sunset,sunrise,park,people,summer,tree,flowers';
            $lat = '&lat='.$latitude;
            $lon = '&lon='.$longitude;
            $perPage = 12;
            $url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search';
            $url.= '&api_key='.$api_key;
            $url.= '&tags='.$tag;
            $url.= $lat;
            $url.= $lon;
            $url.= '&per_page='.$perPage;
            $url.= '&format=json';
            $url.= '&nojsoncallback=1';

            $response = json_decode(file_get_contents($url));
            $photo_array = $response->photos->photo;
            return Response::json(["success"=>"true", "photo_array"=>$photo_array]);

现在在jquery函数中,我正在调用Ajax。

$("#nomination-name").focus(function(){
        $.post(
            '/getlocation/'+$("#newLatitude").val()+"/"+$("#newLongitude").val(), // location of your php script
            { user: "bob", id: 1234 }, // any data you want to send to the script
            function( data ){  // a function to deal with the returned information

                alert(data);

            });
    });

但是当我尝试提醒数据时,它只显示[object Object] 如何在Ajax调用中获得响应? 控制台的输出如下。

Object 
photo_array: Array[12]
0: Objectfarm: 8
id: "16325992992"
isfamily: 0
isfriend: 0
ispublic: 1
owner: "35736862@N03"
secret: "b7044c5b46"
server: "7548"
title: "#snow #trees #winter #parcangrignon #montreal #livemontreal #themainmtl #mtlblog #vscocam"
__proto__: Object
1: Object
..............

1 个答案:

答案 0 :(得分:2)

你想要实现的目标不应该是艰难的。我看不到photo_array的内容,但只要您知道如何遍历对象就可以了。

for(i=0;i<data.images.length;i++) {
    $("#images").append(data.images[i])
}

HTML

<div id="images"></div>

以下是您需要的代码,photo_array可能看起来不一样,但它不应该导致问题只是迭代它。 Here's我测试的链接。