javascript - 在 Jquery 中从 JSON 获取数据

标签 javascript php jquery html json

我有这个 php 文件,它从 instagram API 获取用户信息

<?php

//Get data from instagram api

$keyword = $_GET['keyword'];

if(!isset($_GET['count'])) $count = 20;

else $count = $_GET['count'];


//Query need client_id or access_token

$query = array(
    'client_id' => '8c81a425a76340a79aa66cb88aa74c89',
    'count'     => $count
);

$url = 'https://api.instagram.com/v1/users/search?q='.$keyword.'&'.http_build_query($query);


try {
    $curl_connection = curl_init($url);
    curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);

    //Data are stored in $data
    $data = curl_exec($curl_connection);
    curl_close($curl_connection);
    echo $data;

} catch(Exception $e) {
    return $e->getMessage();
}

?>

并返回包含 20 个用户信息的 JSON 字符串,例如

  {"meta":{"code":200},"data":[{"username":"lama","bio":"","website":"","profile_picture":"http://images.ak.instagram.com/profiles/profile_42284_75sq_1353177507.jpg","full_name":"Li Shing","id":"42284"},{"username":"bekhand_lamasab","bio":"⠀⠀⠀ ⠀⠀ 🍃 Kik : narsis.fashion 🍂\n⠀⠀⠀⠀⠀ ⠀ ⠀ ⚠️ sfs : 520 k ⚠️\n💃شات عضو فعال دوبار درهفته🍂⠀⠀⠀ ⠀⠀ \n🌾توجه🍁تبلیغات تک پیج انجام میشود🌾⠀⠀⠀⠀","website":"","profile_picture":"http://photos-f.ak.instagram.com/hphotos-ak-xap1/10349797_785664258123877_321110299_a.jpg","full_name":"😊بزرگترین پیج ایرانی😊⠀⠀⠀⠀⠀⠀⠀","id":"1085311553"},{"username":"lamarquisette","bio":"","website":"","profile_picture":"http://images.ak.instagram.com/profiles/profile_279115230_75sq_1378119768.jpg","full_name":"Youssef Marquis","id":"279115230"},{"username":"timlaman","bio":"NatGeo Wildlife Photographer - Filmmaker - Field Biologist. Exploring wild places, rare species, rain forests and coral reefs.\nSee more on FB:","website":"https://www.facebook.com/TimLamanPhoto","profile_picture":"http://images.ak.instagram.com/profiles/profile_195678468_75sq_1342554137.jpg","full_name":"Tim Laman","id":"195678468"},{"username":"lamamadelrap","bio":"#RIPMonkeyBlack\n🚫MELYMEL NO UTILIZA FACEBOOK🚫\n(Twitter) @MELYMELMELADA \n(RD) 809.360.9052\n(USA) 347.209.2816","website":"http://www.youtube.com/MelymelVEVO","profile_picture":"http://photos-g.ak.instagram.com/hphotos-ak-xpf1/10693447_660276060736558_41448872_a.jpg","full_name":"MelyMel #zeroDembow","id":"305872466"},{"username":"lamarctaylor","bio":"no reality is the same.","website":"","profile_picture":"http://photos-f.ak.instagram.com/hphotos-ak-xpa1/10731950_736068223151773_567726601_a.jpg","full_name":"lamarctaylor","id":"206461711"},{"username":"lamaisond","bio":"","website":"","profile_picture":"http://photos-g.ak.instagram.com/hphotos-ak-xpa1/10610996_331177297053686_1564957178_a.jpg","full_name":"","id":"1572747"},{"username":"joud_lama","bio":"لا أسمح بحفظ الصور والفديوات\nAll about my kids 👭👶\nOur daily life in videos \nماشاء الله لاقوة الا بالله\nأستودع الله نفسي وعائلتي فاحفظنا من كل شر💕","website":"https://m.youtube.com/watch?v=6PvF2TjuhQw","profile_picture":"http://images.ak.instagram.com/profiles/profile_812908181_75sq_1399322579.jpg","full_name":"Joud_lama","id":"812908181"},{"username":"co._lams","bio":"","website":"","profile_picture":"http://photos-h.ak.instagram.com/hphotos-ak-xpa1/10731956_923164217707383_1481888166_a.jpg","full_name":"Lamar","id":"940742669"},{"username":"lamarca941fm","bio":"","website":"","profile_picture":"http://images.ak.instagram.com/profiles/profile_1173210472_75sq_1394672048.jpg","full_name":"La Marca 94.1 FM","id":"1173210472"},{"username":"jonjonlamar","bio":"#Miami - #NYC. 🇺🇸\nA Private Life is a Happy Life.. ✌️","website":"","profile_picture":"http://photos-e.ak.instagram.com/hphotos-ak-xap1/10483455_526566950776404_1475004702_a.jpg","full_name":"Jonathan Lamar Green","id":"18211272"},{"username":"lamafiabeats","bio":"✔Produccion y promocion de eventos🔥\n✔cuenta aliada @shopvipcaracas👈\n✔publicidad y contacto +58 4242308332","website":"","profile_picture":"http://photos-b.ak.instagram.com/hphotos-ak-xaf1/10731882_609733789138665_677150285_a.jpg","full_name":"la mafia lifestyle","id":"1533879744"},{"username":"marisa_lmp","bio":"🇰🇷 Co-Founder : @micha_thailand\n💁ผลิตภัณฑ์บำรุงผิวหน้า-ผิวกายขาวใส✨\n📲สั่งสินค้า : lmp.marisa/fon-lamapearl✨😻\n📞โทร: 092-2845899 , 085-389-5648 💗","website":"http://www.lamapearl-skincare.com","profile_picture":"http://photos-f.ak.instagram.com/hphotos-ak-xaf1/10731597_1494940657448173_726227876_a.jpg","full_name":"💗CEO of LaMaPearl Skincare💗","id":"10083328"},{"username":"lamaterialista1","bio":"Artista, Actriz, compositora Booking: RD 829-963-3653 USA 917-743-5599 / <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe929f939f8a9b8c979f92978d8a9f9c919195979099be99939f9792d09d9193" rel="noreferrer noopener nofollow">[email protected]</a> / sigueme en twitter @LAMATERIALISTA1","website":"http://www.youtube.com/LaMaterialistaVEVO","profile_picture":"http://photos-c.ak.instagram.com/hphotos-ak-xap1/10665318_743709879028514_706220468_a.jpg","full_name":"LA REINA DE LA CHAPA QUEVIBRAN","id":"177807899"},{"username":"lamaris87","bio":"","website":"","profile_picture":"http://photos-f.ak.instagram.com/hphotos-ak-xpa1/10665398_1493770557570293_1634650289_a.jpg","full_name":"Lamaris","id":"30943990"},{"username":"lamaracuchis","bio":"Animadora de La Bomba \nFashion Blogger\nBlog: http://www.carlafieldproject.com\nChequea mi nuevo tutorial de maquillaje \naquí ⬇ espero lo disfruten.","website":"http://youtu.be/uLLv72vmgG4","profile_picture":"http://photos-a.ak.instagram.com/hphotos-ak-xfp1/891345_637029753056760_2048316896_a.jpg","full_name":"Carla Field","id":"238108076"},{"username":"lamaskeproduce","bio":"Producción de Tv y Radio,influyente,sarcástica,Yal, turista sin visa,Fan d Miley Cyrus,Dra. Polo y Dr. House.❌Cuenta Alterna @lamaskeproducetv","website":"http://www.lamaskeproduce.com","profile_picture":"http://photos-a.ak.instagram.com/hphotos-ak-xap1/925887_491093354357472_430852604_a.jpg","full_name":"Jenifel Galcia Cyrus","id":"30637470"},{"username":"dalailama","bio":"Welcome to the official Instagram Account of the Office of His Holiness the 14th Dalai Lama.","website":"http://www.dalailama.com/","profile_picture":"http://images.ak.instagram.com/profiles/profile_1044003089_75sq_1391167280.jpg","full_name":"Dalai Lama","id":"1044003089"},{"username":"lamarquenyc","bio":"Creative Consultancy co-founded by Meredith Melling and Valerie Boster; la marque, get set, go!","website":"http://lamarquenyc.com","profile_picture":"http://images.ak.instagram.com/profiles/profile_1031042100_75sq_1390883999.jpg","full_name":"la marque","id":"1031042100"},{"username":"lamasat.iq","bio":"➟ Official Account\n| صفحة ترفيهية منوعة |\n❤️لكل العراقيين والعرب❤️\nلا ندعي التميز ولكن نطمح لنكون الافضل \nadmins\nسوسو🌟مشمش🌟مصطفئ","website":"","profile_picture":"http://photos-a.ak.instagram.com/hphotos-ak-xpa1/10755896_316197498569544_758738327_a.jpg","full_name":"❣ لَمّـჰـاتْ عِرّاقـية ❣","id":"1360750684"}]} 

我有一个 html 文件,它将关键字发送到 php 并返回值

<!DOCTYPE html>

<html>
<head>
    <title>jQuery Test</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $("#submit").click(function(){
            $.ajax({
                url: "http://www.lamia.byethost18.com/get_info.php",
                data: {keyword: $("#keyword").val()},
                dataType: 'JSON',
                success: 
                    function(jsonStr) {
                        $.each(jsonStr.data, function(index, element){
                            $("#result").text(element.username);
                            $("#img").attr('src', element.profile_picture);
                        });
                    }
            });
        }); 
    });

    </script>
</head>
<body>

    <div id="result"></div>

    <img src="" id="img" alt="" />
    <form name="contact" id="contact" method="get">
     keyword : <input type="text" name="keyword" id="keyword"/><br/>
    <input type="button" value="search!" name="submit" id="submit"/>
    </form>

</body>

</html>

问题是没有检索到任何内容!我不知道我的代码是否有问题?

我只想使用检索到的数据中的用户名profile_picture并将其显示在标签中。

但没有显示任何内容,我不知道为什么..有人可以帮忙吗?

最佳答案

您可以使用 JSON.parse() 删除该行,因为已经明确设置您将收到 JSON:

dataType: 'JSON',

然后在您的成功 block 中,按如下方式处理:

$.each(jsonStr.data, function(index, element){
    $("#result").text(element.username);
    $("#img").attr('src', element.profile_picture);
});

关于javascript - 在 Jquery 中从 JSON 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26887578/

相关文章:

javascript - Jquery脚本删除表单集合中的所有项目

jquery - 提交前更改输入字段

javascript - 如何使用sqlite在插入查询中获取插入的行id?

javascript - Java 构建器模式可从 Rhino 中的 JavaScript 访问

php - 使用 Eloquent 在 mysql 中左连接后分别获取相同的命名列

php - Woocommerce 电子邮件订单详细信息中的其他列和项目值

javascript - nodejs 异步到同步

javascript - ng-required,如何在输入之间使用它?

php - 为什么这个 ajax 帖子给我一个错误? ajax post是否需要返回 "true"或 "false"?

javascript - 保留前五个字符并在自动完成中 chop 其他字符?