Javascript 简单的ajax调用在django中不起作用
首先,我花了一些时间阅读和理解javascript和ajax,但即使我的代码在与其他类型的代码进行对比时可以正常工作,但这仍然不起作用。我没有做任何花哨的事情,只是返回一个名为info.text的简单文本文件 我使用的是django,这是我创建的简单视图:Javascript 简单的ajax调用在django中不起作用,javascript,python,ajax,django,Javascript,Python,Ajax,Django,首先,我花了一些时间阅读和理解javascript和ajax,但即使我的代码在与其他类型的代码进行对比时可以正常工作,但这仍然不起作用。我没有做任何花哨的事情,只是返回一个名为info.text的简单文本文件 我使用的是django,这是我创建的简单视图: def ajax(request): return render(request, "base/info.text") 下面是简单的ajax/javascript代码: 1 var window, document, submi
def ajax(request):
return render(request, "base/info.text")
下面是简单的ajax/javascript代码:
1 var window, document, submitButton;
2
3 submitButton = document.getElementsByName("form")[0];
4 submitButton.addEventListener("submit", fireAjaxRequest, false);
5
6 function handleResponse() {
7 if (httpRequest.readyState === 4) {
8 alert("response received...");
9 try {
10 alert("in try catch")
11 if (httpRequest.status === 200) {
12 alert(httpRequest.responseText);
13 } else {
14 alert("Request failed, status code received from the server is: " + httpRequest.statusText);
15 }
16 }
17 catch (exception) {
18 alert("exception: " + exception.description);
19 }
20 }
21 }
22
23 function fireAjaxRequest() {
24 console.log("firing the ajax request...");
25 httpRequest = new XMLHttpRequest();
26
27 if (! httpRequest) {
28 alert("not able to create XMLHttpRequest");
29 } else {
30 console.log("created XMLHttpRequest");
31 }
32
33 httpRequest.onreadystatechange = handleResponse;
34 httpRequest.open("GET", "javascript/ajax", true);
35 httpRequest.send(null);
36 console.log("request sent, waiting for response...");
37 }
我知道console.log更好,但当我点击submit按钮时,它会立即清除console.log
在open调用中,除了/javascript/ajax之外,我还尝试了使用它,但这也不起作用
html代码是:
3 <html>
4 <head>
5 <title>Javascript testing</title>
6 </head>
7 <body>
8 Welcome to my site
9 <br><br>
11 <br><br>
12 <form name="form">
13 First name: <input type="text" id="firstName"></input>
14 <br>
15 Last name: <input type="text" id="lastName"></input>
16 <br>
17 <input type="submit" id="submit" value="Send registration">
18 <br>
19 </form>
20 </body>
21 <script type="text/javascript" src="{% static 'js/js_test.js' %}"></script>
22 </html>
py只是指向^javascript/ajax上面的视图
我不明白为什么这个简单的请求不起作用,它没有任何意义
由于某些原因,request.status的输出仅为0。您可能需要捕获并阻止表单上的默认事件 在javascript中尝试以下操作:
function fireAjaxRequest(e) {
// Insert this
e.preventDefault();
24 console.log("firing the ajax request...");
25 httpRequest = new XMLHttpRequest();
26
27 if (! httpRequest) {
28 alert("not able to create XMLHttpRequest");
29 } else {
30 console.log("created XMLHttpRequest");
31 }
32
33 httpRequest.onreadystatechange = handleResponse;
34 httpRequest.open("GET", "javascript/ajax", true);
35 httpRequest.send(null);
36 console.log("request sent, waiting for response...");
37 }
不,我只是向localhost运行这个请求,所以domain.com实际上是localhost stackoverflow的验证不允许我放入localhost。。但无论如何,我会注意到这些链接。请求只是针对一个简单的文本文件,在localhost上只有一行。是的,在这种情况下,这些链接不会有帮助。嗯,好的,我会试试看,我以为我在删除方法和操作时就这样做了,但我还记得,你应该在表单的操作字段中返回一个值