编辑:原始问题已修复。我需要为xmlttp.open()的参数添加协议http:// infront of url。新问题:Django拒绝请求:“POST 127.0.0.1:8000/data 403(FORBIDDEN)”
我有一个通过我的AJAX函数runAJAX()提交的表单。此函数向服务器发出POST请求。问题是服务器没有收到请求。如果不是url参数,如果只为xmlhttp.open()保留url参数为空“”,那么服务器后端的控制台日志会显示正在发出的POST请求,但服务器在这种情况下拒绝它。我的问题是如何成功传递POST请求?我究竟做错了什么?服务器在我的机器上本地托管(127.0.0.1:8000)。连接到127.0.0.1:8000将获取index.html。
点击表单的提交按钮时,浏览器日志中出现错误消息:
XMLHttpRequest cannot load %3127.0.0.1:8000/data/. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
runAJAX @ (index):44
stopDefAction @ (index):51
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load '%3127.0.0.1:8000/data/'.
runAJAX @ (index):44
stopDefAction @ (index):51
我的代码(Javascript,HTML index.html,Django后端urls.py和views.py文件):
function runAJAX(){
xmlhttp.open("POST","127.0.0.1:8000/data/",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var searchtype = document.getElementById("searchtype").innerHTML;
var subreddit = document.getElementById("subreddit").innerHTML;
xmlhttp.send("searchtype=" + searchtype + "&subreddit=" + subreddit);
}
function stopDefAction(evt) {
evt.preventDefault();
runAJAX();
}
document.getElementById('submit').addEventListener(
'click', stopDefAction, false
);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
<div id="center">
<h1 id="h01">Reddit Link</h1>
<p id="p01">A Subreddit Recommender System</p>
<form id="subreddit">
<select id=searchtype name="searchtype" form="subreddit">
<option value="Fast">Fast</option>
<option value="Accurate">Accurate</option>
</select>
<input type="text" name="subreddit" placeholder="AskReddit"/>
<input id="submit" type="submit" value="Search"/>
</form>
<p id="pdone">0%</p>
</div>
Django root urls.py文件:
urlpatterns = [
url(r'', include('redditlink.urls')),]
Webapp urls.py文件:
urlpatterns = [
url(r'^data/$', views.data, name='data'),
url(r'^$', views.index, name='index'),]
views.py文件:
def index(request):
template = loader.get_template('redditlink/index.html')
return HttpResponse(template.render())
def data(request):
print("1")
subreddit_name = request.GET["subreddit"].lower()
search_type = request.GET["searchtype"]