【问题标题】:How would I be able to extract data from an API and display it in a webpage, using DJANGO?如何使用 DJANGO 从 API 中提取数据并将其显示在网页中?
【发布时间】:2020-06-01 02:13:15
【问题描述】:

我收到了一项任务,要求我创建一个网页并使用来自给定 API 的数据填充它。

API 数据采用 REST JSON 格式。此外,我使用 Django 作为框架,因此我避免了跨域请求的任何问题。

我一直在研究请求模块,并且已经达到:

import requests
import pprint
url = ''
r = requests.get(url)
pprint.pprint(r.json()['results'][1])

我可以得到终端机上打印的信息。但是,我对如何在 HTML 页面中实现这一点感到困惑。

我是使用 API 的新手,因此我们将不胜感激。

谢谢

【问题讨论】:

    标签: python django api django-rest-framework


    【解决方案1】:

    我会使用 ajax 在前端使用 api。使用 Pokemon API 进行练习。当然,首先通过 console.log for api 查看您正在使用的内容。获得数据后,将其分配给 html 元素。以下是我使用 jquery 的方法。

    <script 
        src="https://code.jquery.com/jquery-3.5.1.js"
        integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
        crossorigin="anonymous">
    </script>
    
    <script type="text/javascript">
    $.ajax({
        url: 'https://pokeapi.co/api/v2/pokemon/ditto',
        type: 'GET',
        // headers: { "X-CSRFToken" : getCookie("csrftoken") },
        success: function(data) {
            // console.log("sucess From Name choosing", serverResponse);
            // globe variables for clearing table and adding to it
            console.log(data.name);
            document.getElementById("pokemonName").innerHTML = data.name;
            }
    })
    </script>
    <body>
    <h1 id = "pokemonName">This is a Pokemon API playground</h1>
    

    Ajax “获取” api,如果成功,那么 api 会发生某事。 在将 ajax 用于 api 时,您还可以使用其他工具。比如 if 失败的时候。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-20
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 2013-08-06
      • 2021-05-07
      • 2022-01-24
      相关资源
      最近更新 更多