我是javascript的新手,刚刚设置了jquery / ajax并让它在我的Django项目中运行。我尚未修改我的观点以适应GET请求。我的ajax函数正在发送以下请求URL:
http://127.0.0.1:8000/myportfolio/add_transaction/myportfolio/add_transaction
当我希望他们发送时:
为什么会这样?
我的jquery文件:
$(document).ready(function() {
// using jQuery
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]);
// Does this cookie string begin with the name we want?
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) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$('#id_buysell').on('change', function(){
console.log("buysell");
var $formData = $(this).attr("id_buysell");
console.log($formData);
$.ajax({
method: "GET",
url: "myportfolio/add_transaction",
data: $formData,
});
});
$('#id_coin').on('change', function(){
console.log("coin change")
var $formData = $(this).attr("id_coin");
console.log($formData);
$.ajax({
method: "GET",
url: "myportfolio/add_transaction",
data: $formData,
});
});
});
我的观点:
def add_transaction(request):
print(request.method)
print("test1")
form = TransactionForm()
if request.method == "POST":
print("test2")
form = TransactionForm(request.POST)
if form.is_valid():
print("test3")
obj = form.save(commit = False)
obj.user = request.user
obj.save()
return HttpResponseRedirect('/myportfolio/')
else:
print(form.errors)
return render(request, 'myportfolio/add_transaction.html', {'form': form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('add_transaction/', views.add_transaction, name = 'add_transaction'),
path('register/', views.register, name = 'register'),
path('login/', views.user_login, name='login'),
path('logout/', views.user_logout, name='logout')]
答案 0 :(得分:3)
您需要在路径的开头放置一个/
,使其相对于域根而不是当前目录:
$.ajax({
method: "GET",
url: "/myportfolio/add_transaction",
data: $formData,
});