首页 > 解决方案 > 从 promise 对象中获取数据

问题描述

我目前处于需要从 Promise 对象中获取数据以便通过 Vue 更新我的视图的情况。但是我似乎无法从这个承诺对象中获取数据?有谁知道我该怎么做才能从 JSONresponse 访问数据。

请注意,我已发出 POST 请求以创建新的“模块”,现在我需要将这些值传回以更新我的视图。

请在下面找到:

            async createModule() {
              let response = await fetch('create_module', {
                  method: 'POST', // Method itself
                  headers: {
                      "contentType": "application/json",
                      "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken]").value,
                  },
                  body: JSON.stringify({
                      code: document.getElementById('code').value,
                      module_name: document.getElementById('module_name').value,
                      max_students: document.getElementById('max_students').value,
                      start_date: document.getElementById('start_date').value,
                  }) // We send data in JSON format
              });
              if (response.ok) {
                  // module was created
                  //this.modules.push(data);
                  console.log(response.json());  // HERE IS WHERE I AM TRYING TO ACCESS ALL THE VALUES FROM THE RESPONSE

              } else {
                  alert("failed to create module");
              }
          }

我的 API:

def create_module(request):
    """API for creating a module"""
    if request.method == "POST":
        PUT = json.loads(request.body)
        module = Module(module_name=PUT['module_name'], code=PUT['code'], max_students=PUT['max_students'], start_date=PUT['start_date'])
        module.save()
        return JsonResponse({'module_name': PUT['module_name'], 'code': PUT['code'], 'max_students': PUT['max_students'], 'start_date': PUT['start_date']})

    return HttpResponseBadRequest("Invalid method")

感谢您的时间。

标签: javascriptpythonajaxpromisefetch

解决方案


推荐阅读