簡體   English   中英

通過 POST 方法發送數據以顯示在 AJAX 請求中

[英]Sent data through POST method to show in AJAX request

Ajax 方法將字符串發送並傳遞給views.py,views.py 中的post 方法可以從ajax 接收值,但我無法在ajax 成功方法中獲取要打印的結果值。

我試圖返回 HTTPresponse、重定向、渲染,但似乎對我沒有任何作用。

//阿賈克斯//

$("#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. 您可能會在視圖中收到錯誤並且無法注意到它,因為您沒有在 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);
      }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM