【问题标题】:Getting chart.js to work with Django and Apache让 chart.js 与 Django 和 Apache 一起工作
【发布时间】:2018-01-26 00:05:58
【问题描述】:

我有以下设置。我有一个简单的index.html 通过apache 提供服务。如下所示。

<!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 是装饰器。

但是,当我尝试使用 @987654321@ 在浏览器上查看它时,我收到以下错误

XMLHttpRequest 无法加载 http://localhost:8090/polls/alice/。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此,不允许访问 Origin 'http://localhost'。

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

【问题讨论】:

  • customcharts.js 是静态资源吗?
  • 是的,它是一个静态资源

标签: javascript json django jsonp chart.js


【解决方案1】:

如果customcharts.jsstatic/yourapp 内,您需要按如下方式加载脚本:

<script src="{% static 'yourapp/customcharts.js' %}"></script>

别忘了致电{% load staticfiles %}

那么,静态资源不能调用视图,需要获取视图中的json数据,然后传递给javascript函数。

您的模板应如下所示:

{% 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>

希望这会有所帮助。

【讨论】:

  • 我会检查并返回
  • 也许您需要将$.getJSON 函数放入document.ready
  • 当我尝试它时,我得到以下错误 Reverse for 'index' with arguments '()' and keyword arguments '{}' not found。尝试了 2 种模式:['polls/(.*)polls/(.*)$', 'polls/(.*)$'] 我想我必须在“url”中指定参数“alice”索引”的东西不知何故。不知道怎么做。
【解决方案2】:

使用“投票”而不是“索引”

【讨论】:

  • 接近。这似乎只是将我的 json 呈现到浏览器中。我认为没有调用“renderChart”。浏览器上的输出是 {"defaultLabels": ["2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05" , "2017-01-06", "2017-01-07"], "defaultData": ["12", "8", "4", "9", "18", "1", "4" ]} 作为纯文本
  • 使用jquery.parseJson():renderChart(jquery.parseJson(data));
猜你喜欢
  • 1970-01-01
  • 2017-05-08
  • 2011-04-02
  • 2017-09-19
  • 2023-01-24
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
相关资源
最近更新 更多