繁体   English   中英

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

[英]How to get the API request response via AJAX

我正在尝试通过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
..............

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

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

的HTML

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

这是您需要的代码, photo_array看起来可能并不相同,但仅通过它进行迭代就不会引起问题。 这是我测试的链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM