【问题标题】:Ajax returning `none` in djangoAjax 在 django 中返回“none”
【发布时间】:2020-10-08 03:00:13
【问题描述】:

我在一个包含两个button 的表格中保存了这个表格。 代码: index.html

<form action="{% url 'Prediction' %}" method="post">
    {% csrf_token %}
    <table class="table table-striped table-dark" cellspacing="0">
        <thead class="bg-info">
            <tr>
               <th>Company's Symbol</th>
               <th>Current Price</th>
               <th>View Current chart</th>
               <th>Action</th>
            </tr>
        </thead>
        <tbody>
           {% for a,b in stocks %}
               <tr>
                  <th scope="row" class="comp_name">{{ a }}</th>
                  <td>{{ b }}</td>
                  <td>
                     <input type="submit" class="btn graph-btn" formaction="{% url 'Graph' %}" name="_graph" value="View Graph">
                  </td>
                  <td>
                     <input type="submit" class="btn predict-btn" name="_predict" value="Predict Closing Price">
                  </td>
              </tr>
           {% endfor %}
        </tbody>
    </table>
</form>

通过单击.graph-btn,我需要传递单击该按钮的行的数据。这是有效的代码。

<script>
    $(".graph-btn").click(function() {
    var $row = $(this).closest("tr");
    var $text = $row.find(".comp_name").text();
    console.log($text);
    $.ajax({
        type:'POST',
        url:'{% url 'Graph' %}',
        data:{
            text: $text,
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
        },
        success:function(json){
        console.log($text);
        },
        error : function(xhr,errmsg,err) {
        }
    });
});
</script>

但问题是在views.py 返回none

views.py

def graph(request):
    if request.method == 'POST' and '_graph' in request.POST:
        print(request.POST.get('text'))
        # context = {'name': name}
        # # print(name)
        return render(request, 'StockPrediction/chart.html')
    else:
        return render(request, 'StockPrediction/greet.html')

urls.py

urlpatterns = [
    path("", views.greet, name='greet'),
    path("index/", views.index, name='Stock Prediction'),
    path("prediction/", views.prediction, name='Prediction'),
    path("view/", views.graph, name='Graph'),
]

【问题讨论】:

  • 你得到的错误信息是什么?
  • 没有错误。 request.POST.get('text') 正在返回 none
  • console.log($text) 返回正确的值吗?
  • console.log($text)。是的,它返回正确的值。
  • 请帮助我。

标签: python jquery django ajax django-views


【解决方案1】:

尝试将 dataType: 'json' 添加到请求中。例如:

$.ajax({
    type: 'post',
    url: '{% url 'Graph' %}',
    headers: {
        'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val()
    }
    data: {
        text: $text,
    },
    dataType: 'json',
    success: function (data) {
       console.log(data)
    },
    error: function(error) {
       console.log(error)
    }
});

【讨论】:

  • 还是一样。
  • 我认为问题可能 jquery 没有传递值text 或ajax 没有在views.py 中传递给Django。这是正确的方法吗?
  • 你说console.log($text)包含值,所以应该是这样的。
  • 请帮帮我。
【解决方案2】:

在您的视图函数 graph(request) 中,您没有返回值,而是使用请求呈现 HTML 页面。

Django 中的视图函数应该返回 JSON 或字典,或者可以返回网页您可以执行以下任一操作

1) 返回字典或 JSON

return {"key":"value","key":"value"}

2) 返回一个 HttpResponse

return HttpResponse(status_code, response_data)

3) 重定向到另一个页面

return redirect('/some/redirect/url/')

试试上面的方法,如果有帮助就评论

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2020-12-10
    • 2014-08-24
    • 2022-01-13
    • 2020-08-22
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多