让chart.js与Django和Apache一起工作

时间:2017-08-17 14:07:52

标签: javascript json django jsonp chart.js

我有以下设置。我通过apache提供了一个简单的index.html服务。它看起来如下。

<!DOCTYPE html>
<html lang='en'> <meta http-equiv="content-type" content="text/html; charset=UTF8"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <canvas id="myChart"></canvas> <script language="JavaScript" src="/customcharts.js"> </script> </body> </html>

以上所有操作都是尝试在浏览器上放置折线图。它使用chart.js。为此,customcharts.js尝试连接到本地运行的django服务器。上面的html是通过在端口8080上运行的apache提供的,而django是在端口8090上运行的。

customcharts.js如下所示

function renderChart(data){
    console.log(data)
    console.log(data.labels)
    defaultLabels = data.labels
    defaultData = data.defaultData
    var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: defaultLabels,
        datasets: [{
        lineTension: 0,
        label: 'Activity Profile',
        data: defaultData,
        }]
    }
    })
}

var endpoint = 'http://localhost:8090/polls/alice/'
var defaultData = []
var defaultLabels = []

$.ajax({
    url: endpoint,
    dataType: "JSONP",
    success: renderChart,
    method: 'GET'
}
);

此外,我的django视图是

def json_response(func):
    """
    A decorator thats takes a view response and turns it
    into json. If a callback is added through GET or POST
    the response is JSONP.
    """
    def decorator(request, *args, **kwargs):
        objects = func(request, *args, **kwargs)
        if isinstance(objects, HttpResponse):
            return objects
        try:
            data = simplejson.dumps(objects)
            if 'callback' in request.REQUEST:
                # a jsonp response!
                data = '%s(%s);' % (request.REQUEST['callback'], data)
                return HttpResponse(data, "text/javascript")
        except:
            data = simplejson.dumps(str(objects))
        return HttpResponse(data, "application/json")
    return decorator

epoch = datetime.datetime.utcfromtimestamp(0)

r = redis.StrictRedis(host='localhost', port=6379, db=0)
threat_list = ['date', 'categories', 'mix']

@json_response
def index(request, uid):
    print uid
    uid = uid.rstrip('/')
    _key = uid
    retjsondict = {}
    input_keys = [_key + ':' + x for x in threat_list]
    k = input_keys[0]
    retdict = {}
    if r.exists(k):
        retvalue = r.get(k).strip('"')
        xdata_dt = [x.split(':')[0] for x in retvalue.split(' ')]
        ydata_dt = [x.split(':')[1].rstrip(',') for x in retvalue.split(' ')]
        retdict['defaultLabels'] = xdata_dt
        retdict['defaultData'] = ydata_dt
    print retdict
    return JsonResponse(retdict)

index是真实视图,json_response是装饰者。

但是,当我尝试使用 http://localhost在浏览器上查看时,我收到以下错误

  

XMLHttpRequest无法加载http://localhost:8090/polls/alice/。没有   &#39;访问控制允许来源&#39;标题出现在请求的上   资源。起源&#39; http://localhost&#39;因此不允许访问。

有人能指出我做了什么吗? 任何帮助/指示赞赏。

2 个答案:

答案 0 :(得分:1)

如果static/yourapp<script src="{% static 'yourapp/customcharts.js' %}"></script> 范围内,您需要加载脚本,如下所示:

{% load staticfiles %}

不要忘记致电{% load staticfiles %} <!DOCTYPE html> <html lang='en'> <meta http-equiv="content-type" content="text/html; charset=UTF8"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script language="JavaScript" src="{% static 'yourapp/customcharts.js' %}"> </script> <script language="JavaScript"> $.getJSON("{% url 'index' %}", function(data) { // 'index' is the name of the view in your urls.py renderChart(data); }); </script> </head> <body> <canvas id="myChart"></canvas> </body> </html>

然后,静态资源无法调用视图,需要在视图中获取json数据,然后将其传递给javascript函数。

您的模板应如下所示:

{{1}}

希望这有帮助。

答案 1 :(得分:1)

使用'民意调查'代替'索引'