【问题标题】:Error in sending response from python to Ajax从 python 向 Ajax 发送响应时出错
【发布时间】:2021-03-10 19:37:47
【问题描述】:

当控制来自文本字段时,我正在调用一个脚本,该脚本又调用一个 python 函数来返回响应。调用函数时出现错误::POST http://127.0.0.1:8000/getcustomernamefromexcel 403 (Forbidden)

包含脚本的 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 && 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')

【问题讨论】:

  • 尝试使用JsonReponse 而不是HttpResponse。例如,试试这个:return JsonResponse({ 'msg': 'html' })。从django.http 导入JsonResponse

标签: javascript python html django ajax


【解决方案1】:

HTTP 403 表示服务器拒绝您的查询,因为您没有授权。您不应该在标头、cookie 或其他内容中发送任何授权吗?

检查服务器代码的认证部分

另一个错误在您的服务器代码中,因为您没有发送授权,它应该以 401 响应。

【讨论】:

    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2020-03-06
    • 2021-03-20
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多