使用 javascript fetch 调用后端 url 时无法在 django 视图中 render()

问题描述 投票:0回答:1

我使用 javascript 进行表单验证,并使用 fetch 调用后端 api,后端由 django 处理,然后 api 关联的视图正在渲染具有某些上下文的页面,但响应将返回 fetch 而不是返回 html 页面所以我想用一些上下文来渲染页面 我该怎么做

javascript 表单验证

try {
        const response = await fetch("/save_dependent", { // Ensure you replace "/save_dependent" with your actual endpoint
            method: "POST",
            headers: {
                "X-CSRFToken": document.querySelector('input[name="csrfmiddlewaretoken"]').value, // Pass the CSRF token in the request headers
                // Do not set 'Content-Type' manually; let the browser handle it for multipart/form-data boundary
            },
            body: formData,
        });
        if (response.ok) {
            let data = await response.text(); 
            console.log('Server Response:', data);

        } else {
            // Handle HTTP error responses (e.g., 400, 401, 403, 404, 500)
            console.error('Server responded with non-OK status:', response.status);
        }
        } catch (error) {
        console.error('Error:', error);
    }

views.py

@login_required(login_url='auth/signin')
def save_dependent(request):
    # print('request.data: ',request.data)
    print("POST data:")
    for key, value in request.POST.items():
        print(f"{key}: {value}")
    if request.method == 'POST':
        uploaded_file = request.FILES.get('dependent_docs')
        print('uploaded_file ',uploaded_file)
        if uploaded_file:
            # Handle file processing
            print(f"Received file: {uploaded_file.name}")
            save_path = os.path.join(SETTINGS.BASE_DIR, 'static', 'assets', 'img', 'beyond_border_dependents_doc', uploaded_file.name)
            try:
                # Writing the uploaded file to the specified directory
                with open(save_path, 'wb+') as destination:
                    for chunk in uploaded_file.chunks():
                        destination.write(chunk)
                print('returning....')
                return render(request, 'nhcp_registration_test.html',{'dependent_saved':'successs'})
                # return HttpResponse("File uploaded successfully")
            except Exception as e:
                # Handle exceptions that occurred during file upload
                print(f"Failed to upload file. Error: {e}")
                return HttpResponse("Failed to upload file.", status=500)
        else:
            print('in else of uploaded_file')
            return render(request, 'nhcp_registration.html',{'dependent_saved':'successs'})
    print('at last return')    
    return render(request, 'nhcp_registration_test.html')

我希望视图渲染带有一些上下文的 html 页面,但是当我使用 fetch 调用后端 api 时,视图的输出将返回到 fetch 的响应 但我想用上下文渲染页面

我尝试使用 document.documentElement.innerHTML = data; 渲染视图的输出(这是一个带有上下文的 html 页面)。 但它不起作用,我不认为这是最好的方法,那么我如何使用视图重新显示的上下文来渲染 html 页面

javascript validation django-views fetch-api render
1个回答
0
投票

您似乎想使用从 Django 视图返回的 HTML 和上下文动态更新当前页面。不要使用

response.text()
获取 HTML 并尝试替换整个页面的内容,而是考虑以不同的方式处理响应。

在 JavaScript 中,您可以按如下方式修改代码:

// Inside the try block
if (response.ok) {
    let responseData = await response.json(); // Assuming your Django view returns JSON
    console.log('Server Response:', responseData);

    // Modify this part based on your JSON structure
    if (responseData.redirect) {
        window.location.href = responseData.redirect; // Redirect to the new page
    } else {
        // Update specific elements on the current page if needed
        document.getElementById('someElement').innerHTML = responseData.someData;
        // Add other handling as per your requirements
    }
} else {
    // Handle HTTP error responses
    console.error('Server responded with non-OK status:', response.status);
}

在 Django 视图中,确保返回 JSON 响应:

from django.http import JsonResponse

# Inside your view
# ...

return JsonResponse({'redirect': '/new_page_url', 'someData': 'your_data'}, safe=False)

这样,您的 Django 视图可以指定是否重定向到新页面(

redirect
键)或更新当前页面上的元素(
someData
键)。根据您实际的 JSON 结构和需求调整代码。

© www.soinside.com 2019 - 2024. All rights reserved.