我正在尝试通过ajax发送帖子请求,但是ajax似乎没有被解雇。在create_post()
中,console.log("i'm clicked");
会显示在控制台中。 monthly_query(request)
中的打印语句不会显示在日志中。
HTML:
<form method="POST" action="/create_post/" id="post-form">
<select id = "datasource">
<option value="data1">data1</option>
<option value="data2">data2</option>
</select>
<select id="sourceyear">
{% for year in years %}
<option value="Years">{{ year }}</option>
{% endfor %}
</select>
<select id="sourcemonth">
<option value="Monthly">1</option>
<option value="Monthly">2</option>
<option value="Monthly">3</option>
<option value="Monthly">4</option>
</select>
<input type="button" value="Submit" onclick="create_post()"/>
{% csrf_token %}
</form>
使用Javascript:
$(document).ready(function() {
$('#post-form').on('submit', function(event) {
event.preventDefault();
});
function create_post() {
console.log("i'm clicked");
$.ajax({
url: "create_post/",
cache : "false",
type: "POST",
dataType: 'json',
data : { 'source': $("#datasource").val(), 'year': $("#sourceyear").val(), 'month': $("#sourcemonth").val() },
success : function(json) {
console.log("my json")
$("#outgoingvalue").prepend(json.result);
},
error: function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
}
views.py:
def monthly_query(request):
print("request made")
if request.method == 'POST':
print("post request success")
urls.py:
urlpatterns = patterns (
'',
url(r'^$', views.metrics, name='metrics'),
url(r'^api/graphs', views.graphs, name='graphs'),
url(r'^create_post/$', views.monthly_query, name='create_post'),
)
编辑: 额外的javascript:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
//test that a given url is a same-origin URL
//url could be relative or scheme relative or absolute
var host = document.local.host;
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
return (url == origin || url.slice(0, origin.length + 1) == origin +'/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
!(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if(!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
编辑:
输出beforeSend: function(xhr, settings)
console.log(settings);
:Object {url:&#34; / create_post /&#34;,type:&#34; POST&#34;,isLocal:false,global:true,processData:true,async:true,contentType :&#34; application / x-www-form-urlencoded; ...&#34;,接受:对象,内容:Object,responseFields:Object,14 more ...}
答案 0 :(得分:1)
在您的ajax请求中,您要求create_post/
这是一个相对网址。因此,如果您在/home/
,请求将发送到/home/create_post/
。您应该使用相对于root的路径。所以它应该是/create_post
。
print
会在您的控制台上显示该消息,但它不会将该字符串作为html响应发送。
你需要处理csrf令牌。最好将其作为请求的一部分传递或免除它。
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def monthly_query(request):
print("request made")
if request.method == 'POST':
return HttpResponse("post request success")
您需要从视图中返回HttpResponse
,以便将其作为来自服务器的响应发送。 csrf_exempt
装饰器将使视图免于csrf保护。
您可以像这样导入:
from django.http import HttpResponse