Ошибка при отправке ответа из python в Ajax

#javascript #python #html #django #ajax

#javascript #python #HTML #django #ajax

Вопрос:

Когда управление выходит из текстового поля, я вызываю скрипт, который, в свою очередь, вызывает функцию python для возврата ответа. при вызове функции я получаю сообщение об ошибке::POST http://127.0.0.1:8000/getcustomernamefromexcel 403 (Запрещено)

Html-файл, включающий скрипт :

     {% extends 'base.html' %}
<html>
<body>
{% block content %}
    <script type ="text/javascript">
      function getCustomerName() {
        var x = document.ipwhitelistindex.AWSID.value;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 amp;amp; this.status == 200) {
      document.ipwhitelistindex.getElementById("CUSTNAME").innerHTML  = this.responseText;
    }
  };
  xhttp.open('POST', 'getcustomernamefromexcel', true);
    xhttp.send(x);
       }
    </script>
    <h1>IP Whitelisting</h1>
    <form name = "ipwhitelistindex" action = 'ipwhitelisting' method = "post">
        {% csrf_token %}
        <center>
            <table>
        <tr><td>Enter AWS Account Id </td><td>:</td><td><input type = 'text' name = AWSID onblur="getCustomerName()"></td></tr>
        <tr><td>Customer Name </td><td>:</td><td><input type = 'text' name = CUSTNAME style = "background-color : lightgrey" readonly></td></tr>
        <tr><td>Enter list of IPS seperated with(,) </td><td>:</td><td><input type = 'text' name = IPS></td></tr>
        <tr><td>Enter description </td><td>:</td><td><input type = 'text' name = DESC></td></tr>
            </table><br>
            <input type = 'submit' value = 'submit'>
        </center>
    </form>
{% endblock %}
</body>
</html>
 

код python :

  def getcustomernamefromexcel(request):
    return HttpResponse('html')
 

Комментарии:

1. Попробуйте JsonReponse вместо HttpResponse . Например, попробуйте это: return JsonResponse({ 'msg': 'html' }) . Импорт JsonResponse из django.http .

Ответ №1:

HTTP 403 означает, что сервер отклоняет ваш запрос, потому что у вас нет авторизации. Вы не должны отправлять какие-либо авторизации в заголовке, cookie или что-то еще?

Проверьте часть аутентификации в коде разделения

Еще одна ошибка в коде вашего сервера, поскольку вы не отправили авторизацию, предполагается, что он ответит 401.