【问题标题】:django ajax javascript not workingdjango ajax javascript不工作
【发布时间】:2017-06-06 06:21:26
【问题描述】:

1。我正在尝试将 ajax 添加到我的 django Web 应用程序中...我编写的代码如下...为了测试我想在 id="id_ajax1" 的 html 元素中显示一个文本...代码成功显示文本,但它会再次自动重新加载页面...

2。当我从这一行下面给出的代码中编写第一个时,行为如上所述......当我从下面的代码中编写第二个时,它显示 broken pipe ('127.0.0.1', 46958)

return HttpResponse("text to be returned asynchronously")

return HttpResponse("text to be returned asynchronously", mimetype="application/javascript")

代码:

ajax.html

<form action onsubmit="ajax1()">
 <span id="id_ajax1"></span>
 <button class="col-5" type="submit">click</button> 
</form>

ajax.js

function ajax1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("id_ajax1").innerHTML = this.responseText;
        }
    };

    var url = "test/ajax1";
    xhttp.open("GET", "/test/ajax1", true);
    xhttp.send();
}

urls.py

urlpatterns = [
    url(r'^test/ajax1/$', views.ajax1, name='ajax1'),
]

views.py

def ajax1(request):
    return HttpResponse("You have successfully written your first ajax code")

【问题讨论】:

    标签: javascript ajax django python-2.7


    【解决方案1】:

    有多个问题可能导致此行为:

    1. 您正在提交表单,因此重新加载页面。 ajax1() 函数应返回 false 以防止浏览器自动发送表单。
    2. xhr.open()中使用的url与urls.py中定义的url不同
    3. 我不确定是什么导致了管道损坏错误。这可能是mimetype。 application/javascript 用于将实际的 Javascript 代码发送到浏览器。发送文本(如使用 AJAX)所需的 mimetype 是 text/plain。在您的情况下,根本不需要定义 mimetype。

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多