javascript - 将 Fetch 与 Javascript 和 Django 结合使用

标签 javascript django fetch

我是 Javascript 的新手,我正在使用 Django。

我已经阅读了有关 Javascript fetch API 的文档,但我对某些事情感到困惑 - 如果有人能解释一下,我将不胜感激。

我见过不包含 API URL 的代码。这是从框架内哪里来的 - 当我编写代码时,我怎么知道在获取部分之后放什么?

例子:

const load_like = (post, postLikes, likePost, current_user) => {
    const csrftoken = getCookie('csrftoken');
    fetch(`/post/${post.id}`, {
        method: 'PUT',
        body: JSON.stringify({
            likes: [post.original_poster.id]
        }),
        headers: { "X-CSRFToken": csrftoken }
    })
        .then(response => response.json())
        .then(data => {
            display_likes(data, postLikes, likePost, current_user)
        })
}

这是在 urls.py 中完成的吗? 例如:

 path("post/<int:post_id>", views.post, name="post" ),

我想确保我了解如何编写此类行并了解为什么这些部分应该放在这里:

fetch(`/post/${post.id}

最佳答案

所以我对此也是新手,但这是我的方法。我不确定您是否会在生产中这样做。

这是我最近的一个项目中的一个例子。该项目中的一个应用程序称为 packaging,因此示例来自此应用程序。

打包app的urls.py:

app_name = "packaging"
urlpatterns = [
    ...
    path("brand/<str:brand_id>", views.brand_info, name="brand_info"),
    ...
]

views.py(此 View 呈现 html 页面并将上述 url 反转到模板中):

@login_required
def package(request):
    try:

        brand_information = reverse('packaging:brand_info', args=['brand_id'])

        return render(request, "packaging/package.html", {
            ...
            'brand_information' : brand_information,
            ...
            })

    except Exception as e:
        print(e)
        return render(request, "packaging/package.html")



# The view, `brand_info` returns some information about the brand as a JsonResponse.


然后,在 package.html 中,我使用模板标签提取反向 url 以使其可用于 JavaScript 文件:

{{ brand_information|json_script:"url_brand_info" }}

上面的模板标签是一个以 url_brand_info 作为 id 的元素。

现在,在您的 JavaScript 文件中:

function func_to_get_brand_info(id) {

    let url_string = JSON.parse(document.querySelector('#url_brand_info').textContent);
    // Here, the url_string looks like this: "/packaging/brand/brand_id".
    // We want to replace the last part of the string with the actual brand id

    let url_base = url_string.split('brand_id')[0];

    // making a valid url to hit with the fetch
    let url = `${url_base}${id}`;            // NOTE These are backticks not quotes



    // Or, if you don't want to use the dynamic method,
    // you can just hardcode the url in the fetch like:
    // fetch(`/packaging/brand/${id}`, {
    // ...
    // }
    // Here, the '/packaging/brand/' is the url that is in my urls.py file when resolved.
    // This is what is in your example, the url is hardcoded but the id is dynamic.


    fetch(url, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        result = response.json()
        status_code = response.status;
        if(status_code != 200) {
            console.log('Error in getting brand info!')
            return false;
        }
        
        return result
    })
    .then(result => {
        console.log(result);

        // Do something with the result

    })
    .catch(error => {
        console.log(error)
    })


}

关于javascript - 将 Fetch 与 Javascript 和 Django 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67188765/

相关文章:

javascript - 选择多个实例中的第一个

javascript - 将 Promise 绑定(bind)到函数

python - Django:如何在对象创建期间更新另一个模型的字段

Django 站点 : Where to store SQL setup commands?

javascript - 新的 FormData 返回空对象

javascript - ionic 框架 - Angular html 包含

javascript - 一个表情符号只能预览一次

django - Python-social-auth:禁用自动注册新用户

javascript - React 中嵌套获取请求的问题

javascript - 服务器上的文件更改了内容,但 js 仍然获取旧数据