Django:无法从Javascript调用python函数

时间:2016-06-21 15:04:44

标签: javascript python angularjs django

我有一个具有以下结构的Django项目。我的项目名称是 SimpleWeb 。我有一个名为 query 的应用程序。现在我有一个HTML页面,它有一个下拉菜单和一个提交按钮。

这是我想要做的。当用户从下拉列表中选择一个项目并点击提交时,我想在我的view.py文件中调用python函数,对该项执行某些操作并返回列表。

问题是我认为我的函数runQuery由于某种原因没有被调用。以下是我的代码

SimpleWeb \ urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^runQuery/$', include('query.urls')),
    url(r'^$', include('query.urls')),
]

查询\ urls.py

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

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^runQuery', views.runQuery, name='runQuery'),
]

view.py

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    # this function powers the main page: 'http://127.0.0.1:8000/'
    List = ['item1','item2','item3']
    return render(request, 'query/home.html', {'list': List})


def runQuery(request):
    # this function needs to be called using $http from javascript 
    # I want to get what user submitted in $http and do something with it here
    # then return a list, below is a sample list 
    fruitList = ['apple', 'banana', 'orange']
    return HttpResponse(fruitList)

的script.js

angular.module('myApp', []);
angular.module('myApp').controller('myCtrl', ['$scope', '$http', function ($scope, $http) {

$scope.submitButtonclicked = function(){
    var userInput = $scope.data.dropdown /* item that user chooses from dropdown*/

    $http({
        method: 'GET',
        url: '/runQuery',
        params: {yourChoice: userInput}
    }).then(function successCallback(response){
        console.log(response); /* When I debug in chrome browser, I see that it logs an HTML page as the response instead of fruit list */
    }, function errorCallback(response) {
        console.log("Oops, error occurred");
    });
 };
}]);

同样,我发布了大部分我认为相关的代码,可能会帮助您找到解决方案。我的同事告诉我,我在runQuery文件中定义urls.py的方式可能搞砸了,这就是为什么runQuery()函数没有被正确调用的原因。我不知道如何解决这个问题。谢谢你:))

2 个答案:

答案 0 :(得分:1)

你的同事是对的,你在urls.py定义中是多余的。

目前,只使用您的主应用SimpleWeb/urls.py并从那里构建您的网址。完成后,您可以学习如何将它们分成几部分并导入它们。

我猜这些是您要查找的网址。

# SimpleWeb/urls.py
urlpatterns = [
    url(r'^$', query.views.index),
    url(r'^runQuery$', query.views.runQuery),
]

下一个问题是你运行查看视图,因为它返回list,但它必须返回str

def runQuery(request):
    fruitList = ['apple', 'banana', 'orange']
    return HttpResponse(fruitList)  # --> error: this is not a str!

使用Django's JsonResponse()将列表作为JSON编码字符串返回。

def runQuery(request):
    fruitList = ['apple', 'banana', 'orange']
    return JsonResponse(fruitList)

答案 1 :(得分:1)

您没有正确定义URL,因此路由器无法找到正确的方法。您可以通过以下方式定义网址:

<强> SimpleWeb \ urls.py

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'', include('query.urls')),
]

<强>查询\ urls.py

from django.conf.urls import include, url
from . import views
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^runQuery', views.runQuery, name='runQuery'),
]

<强> view.py

这里需要返回一个JSON对象。使用HttpResponse返回它的一种方法是使用simplejson。

from django.shortcuts import render
from django.http import HttpResponse
from django.utils import simplejson

def index(request):
     # this function powers the main page: 'http://127.0.0.1:8000/'
     List = ['item1','item2','item3']
     return render(request, 'query/home.html', {'list': List})


def runQuery(request):
    # this function needs to be called using $http from javascript 
    # I want to get what user submitted in $http and do something with it here
    # then return a list, below is a sample list 
    fruitList = simplejson.dumps("fruitlist" : ['apple', 'banana', 'orange'])
    return HttpResponse(fruitList, content_type ="application/json")