我是 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/