使用Django在外部JS文件中发布AJAX

时间:2016-05-11 11:01:32

标签: javascript ajax django

我试图从我的一个Django网页发出一个AJAX帖子请求,但它不起作用。我怀疑这个问题是由于我不知道如何正确引用外部javascript文件(位于静态文件夹的子文件夹中)中的URL。我的Javascript文件中间的窗口警报显示正确,所以我知道代码正在执行,但POST没有发生。

非常感谢您提供有关如何解决此问题的任何指示。

Views.py:

@csrf_exempt
def survey(request):
   survey_response = Post.objects.all()
   post = Post.objects.get(question=u'Are you happy with your waste management services?')

    if request.method == 'POST' and request.POST['start[action]']=="geolocation":
      latitude = request.POST['start[latitude]']
      longitude = request.POST['start[longitude]']

    if request.method == 'POST' and request.POST['start[action]']=="ethereum":
      transaction_id = request.POST['start[transaction_id]']
      print transaction_id

    return render(request, 'poll/survey.html', {'survey_response': survey_response})

Urls.py:

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^survey/', views.survey, name='survey'),]

Javascript摘录(位于static / poll / javascript / votes.js)

function yesVote(){
var transaction_ID= sendM.increaseYes.sendTransaction({from:council});
sendTransaction(transaction_ID);
}

function noVote(){
var transaction_ID=sendM.increaseNo.sendTransaction({from:council});
sendTransaction(transaction_ID);
}

function sendTransaction(transaction_ID){
var ethereum = "ethereum";
window.alert("HI");
$.ajax({
url: "/survey/",
type:"POST",
data: {start:{
  action:ethereum,
    transaction:transaction_ID}
  },
dataType:'json',
success: function(data){
alert('success'+data);
}
})}

1 个答案:

答案 0 :(得分:0)

views.py中有一个错误,错误地将来自AJAX帖子的数据引用为['start [transaction_id]']而不是['start [transaction]']

if request.method == 'POST' and request.POST['start[action]']=="ethereum":
  transaction_id = request.POST['start[transaction]']