python - 通过POST方法发送数据以在AJAX请求中显示

标签 python django ajax django-class-based-views

Ajax方法发布并将字符串传递给views.py,views.py中的post方法可以从ajax接收值,但我无法在ajax成功方法中获取要打印回的结果值。

我尝试返回 HTTPresponse、重定向、渲染,但似乎没有任何效果。

//Ajax//

$("#viewData").click(function(event){

                $.ajax({
                    type: "POST",
                    data: {
                        tempData : "permView",
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                    },
                    success: function(result) {
                        console.log('{{ result }}')
                    },

                });
                event.preventDefault()
            });
        });

//Python//views.py

class SpreadSheetView(TemplateView):
    template_name = 'spreadsheet.html'

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {'type': '86'})

    def post(self, request):
        if request.POST['tempData'] == 'permView':
            return render(request, self.template_name, {'result': "test result"})

最佳答案

您遇到以下两个问题之一:

  1. 您的 View 中可能会出现错误,但您无法注意到它,因为您没有在 ajax 请求中涵盖错误情况。只需像这样更新您的 ajax 请求调用,然后查看是否收到错误。
  2. 您没有为请求指定 dataType 参数,这会导致 ajax 错误地猜测您的响应类型。

要涵盖这两项,请更新您的请求,例如:

$.ajax({
      type: "GET",
      dataType : 'html', # or other types, depending on your needs.
      data: {
          tempData : "permView",
          csrfmiddlewaretoken: '{{ csrf_token }}',
      },
      success: function(data, status) {
          console.log(data)
          console.log(status)
      },
      error: function(xhr, status, error) {
          console.log(status);
          console.log(error);
      }
});

关于python - 通过POST方法发送数据以在AJAX请求中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57552907/

相关文章:

python - 使用 python 和 pandas 按季节分组数据

python - 使 VS Code 在已经运行的终端(Ubuntu)中执行 python 脚本

javascript - 多次提交表单

python - 为什么 re.match ("c", "cat") 不返回 true?

python - 在 matplotlib 中添加新的导航模式

django - django 管理目录除了保存命令目录之外还有什么用?

python - PyCharm 在 2016.1.2 中不再自动完成 Django 模型查询

python - Django预取相关和选择相关

javascript - .load() 在 DOM 中的另一个 div 之前添加一个 div(不是内部)

javascript - 如何通过表jquery中的onclick获取一些数据列和标题