【问题标题】:Javascript ajax call doesn't trigger DjangoJavascript ajax 调用不会触发 Django
【发布时间】:2014-06-18 15:02:01
【问题描述】:

我正在尝试根据从下拉栏中选择的内容来更改页面上的某些文本,但无法让我的 javascript 调用我的 Django 函数来确定文本,因此永远不会替换占位符文本.

JS:

function updateDateRange(){
  text = "";
  $.ajax({
    url:'/report/api_report_dates/',
    data: {'option':selection_criteria_date[0]},
    type: 'POST',
    error: function(){alert('Error!');},
    success: function(){
        text = "Date Range: " + infoDict['start_date'] + " to " + infoDict['end_date'];
    },
  });

urls.py:

(r'^report/$', 'report_view.view_report'),
(r'^report/api_report', 'report_view.api_report'),
(r'^report/api_report_dates', 'report_view.api_report_dates'),

report_view.api_report_dates:

def api_report_dates(request):
    infoDict = {}
    infoDict['start_date'] = (gets start date from request.option, else is "")
    infoDict['end_date'] = (gets end date from request.option, else is "")
    return HttpResponse(json.dumps(infoDict), content_type="application/json")

占位符文本出现在选择选项之前应出现的位置,并显示“完成!”警报在我期望的时候出现。但它永远不会更改文本,我在 report_view.api_report_dates 的开头设置了一个断点,但调试器从不点击它,除非在页面加载时。

任何帮助将不胜感激!

编辑: dhana 的回复帮助了我,更新了代码以反映当前状态。我现在的问题是 ajax 既没有进入“错误”也没有进入“成功”子句。

如果版本很重要,本网站使用 Django 1.2 和 JQuery 1.4.2

【问题讨论】:

  • 您需要将所有逻辑移动到success 回调中 - 无法在它之外访问。
  • 如果这是您的逐字代码,那么在您的成功函数中,您的引号会被弄乱。应该是text = "Date Range:" + infoDict['start_date'] + " to " + infoDict['end_date'];
  • 另外你的成功函数没有参数,所以你没有存储来自服务器的响应。
  • 感谢化名!只是缺少成功参数。此外,引号只是复制时的拼写错误。

标签: javascript jquery python ajax django


【解决方案1】:

你应该这样写,

function updateDateRange(){
  $.ajax({
    url:'/report/api_report_dates/',
    data: {'option':selection_criteria_date[0]},
    type: 'POST',
    error: function(){alert('Error!');},
    success: function(){
alert('Done!');

  text = "Hello!"
  if (infoDict['start_date'] != '') {
    text = "Date Range: " + infoDict['start_date'] + " to " + infoDict['end_date'];
  } 

},
  }); //returns infoDict with 'start_date' and 'end_date'

在 urls.py 文件中添加这个

(r'^report/api_report_dates/$', 'report_view.api_report_dates'),

在report_view.api_report_dates 中:

import json

def api_report_dates(request):
    infoDict = {}
    infoDict['start_date'] = "some date"
    infoDict['end_date'] = "some date"
    return HttpResponse(json.dumps(infoDict))

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 2017-06-10
    • 1970-01-01
    • 2012-11-25
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 2013-06-19
    相关资源
    最近更新 更多