2015-09-30 31 views
0

我开始在一个简单的web应用程序,我试图调用一个python函数来通过ajax调用渲染一个单独的视图。我想单击试试按钮并呈现不同的html模板。现在它只是显示来自我的ajax的错误消息,但我不知道什么可能会打破它。我只需要有人指点我正确的方向。某种程度上的出发点将不胜感激。感谢提前:)如何通过django项目中的ajax调用来调用python函数?

我的项目urls.py看起来像这样

from django.conf.urls import include, url, patterns 
from django.conf.urls.static import static 
from django.contrib.staticfiles.urls import staticfiles_urlpatterns 
from SudokuProject import settings 

urlpatterns = patterns('', 
url(r'', include('SudokuApp.urls', namespace="Sudoku"))) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

urlpatterns += staticfiles_urlpatterns() 

我的应用程序urls.py

from django.conf.urls import include, url 
from . import views 

urlpatterns = [ 
    url(r'Home/', views.sudoku_home, name="home"), 
    url(r'Solve/', views.sudoku_solve, name="solve") 
] 

Views.py

from django.shortcuts import render 
from django_ajax.decorators import ajax 

def sudoku_home(request): 
    return render(request, 'SudokuHome.html') 

@ajax 
def sudoku_solve(request): 
    return render(request, 'SudokuSolve.html') 

$(document).ready(function(){ 
 
    $('#try').click(function() { 
 
     alert('hi'); 
 
     $.ajax({ 
 
      url:"{% url 'Sudoku:solve' %}", 
 
      type:"POST", 
 
      success: function (data) { 
 
       alert('woohoo success'); 
 
      }, 
 
      error: function(data) { 
 
       alert("something's wrong"); 
 
      } 
 
     }) 
 
    }); 
 
});
<body> 
 
    Hello Welcome to Sudoku 
 
    <button id="try">try me</button> 
 
</body> 
 

 
<script type="text/javascript" src="{% static 'js/jquery.js' %}" ></script>

+0

什么错误信息,你得到什么?可能是一个csrftoken错误? –

+0

我刚刚得到了我在ajax错误提示下的警告,“出错了” – hotkoreanchick

回答

0

我相信你正在使用django-ajax库,并且你已经安装了它。

django-ajax documentation,你必须返回一个字典:

@ajax 
def my_view(request): 
    c = 2 + 3 
    return {'result': c} 

# The result is send to the browser in the following way (JSON format) 

{"status": 200, "statusText": "OK", "content": {"result": 5}} 

所以,你的函数应该返回是这样的:

@ajax 
def sudoku_solve(request): 
    return { "message": "hello world!" } 

而且你可以使用这些数据您前端为:

... 
     success: function (data) { 
      alert(data.content.message); 
     }, 
... 
+0

没错,但是我的目标不是发送一个字符串..我想渲染一个完全不同的页面,这一直是可能的某种方式:/ – hotkoreanchick

+0

@hotkoreanchick检查文档:https://github.com/yceruto/django-ajax#ajaxmixin-for-class-based-views – ezdookie

+0

嘿,所以我试着返回一个简单的字符串就像你发布的一个,消息,但我似乎无法成功地对返回的数据做任何事情。 Ajax总是出错,为什么? – hotkoreanchick

0

您需要呈现模板,然后发回一个字符串,像这样:

from django.template.loader import render_to_string 

def sodoku_solve(request): 
    html = render_to_string('SodukuSolve.html') 
    return {'html': html} 

在您的客户端:

success: function(data) { alert(data.content.html); } 
+0

试过,但没有真正的工作。看来,我的阿贾克斯从来没有成功。即使当我尝试返回一个简单的字符串,我似乎无法成功。任何想法为什么? – hotkoreanchick

+0

在您的Ajax调用中将您的请求类型从POST更改为GET –

相关问题