首先,我花了时间阅读和理解javascript和ajax,但即使我的代码在检查其他类型的代码时也会正常工作,但它似乎完全一样,但仍然不起作用。我在这里没有做任何花哨的事情,只是返回一个名为info.text的简单文本文件
我使用django,这是我创建的简单视图:
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“之外,我还尝试了使用"http://domain.com:8000/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>
urls.py只是指向上面的视图(^javascript/ajax)。
我不明白为什么这个简单的要求不起作用,它没有任何意义。
由于某种原因,request.status的输出仅为0。
发布于 2014-05-27 17:39:22
您可能需要捕捉并防止表单上的默认事件。
在您的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 }
https://stackoverflow.com/questions/23895595
复制相似问题