将Fetch与Javascript和Django一起使用

将Fetch与Javascript和Django一起使用,javascript,django,fetch,Javascript,Django,Fetch,我是Javascript新手,正在使用Django 我已经阅读了有关Javascript获取API的文档,但我对一些事情感到困惑——如果有人能解释一下,我将非常感激 我见过没有包含API url的代码。这在框架中是从哪里来的?当我编写代码时,我如何知道在获取部分之后应该放什么 例如: const load_like = (post, postLikes, likePost, current_user) => { const csrftoken = getCookie('csrfto

我是Javascript新手,正在使用Django

我已经阅读了有关Javascript获取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)
        })
}
这是在url.py中完成的吗? 例如:

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

所以我对这一点也不熟悉,但这是我的方法。我不确定你在生产中是否会这样做

下面是我最近的一个项目中的一个例子。项目中的一个应用程序名为
打包
,因此示例来自此应用程序

打包应用程序的URL.py:

app_name = "packaging"
urlpatterns = [
    ...
    path("brand/<str:brand_id>", views.brand_info, name="brand_info"),
    ...
]
然后,在
package.html
中,我使用模板标记提取反向url,使其可用于JavaScript文件:

{{ brand_information|json_script:"url_brand_info" }}
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)
    })


}
上面的模板标记是一个元素,其id为
url\u brand\u info

现在,在JavaScript文件中:

{{ brand_information|json_script:"url_brand_info" }}
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)
    })


}
这是一个相对的url。打开浏览器开发工具控制台(键盘上的F12)并粘贴到
位置。href='/tags'
,然后按Enter键,浏览器将加载此站点上的根相对路径