我目前正在学习golang和一些Webstuff。所以请原谅我可能不是那么聪明的问题

我的问题是我想为Highchart提供动态数据。我查阅了文档和示例,但无法正常工作。

Highchart示例:

        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
    <script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>


    <!-- 2. Add the JavaScript to initialize the chart on document ready -->
    <script>
    var chart; // global

    /**
     * Request data from the server, add it to the graph and set a timeout to request again
     */
    function requestData() {
        $.ajax({
            url: 'http://localhost:3000/',
            success: function(point) {
                var series = chart.series[0],
                    shift = series.data.length > 20; // shift if the series is longer than 20

                // add the point
                chart.series[0].addPoint(eval(point), true, shift);

                // call it again after one second
                setTimeout(requestData, 1000);
            },
            cache: false
        });
    }

    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                defaultSeriesType: 'spline',
                events: {
                    load: requestData
                }
            },
            title: {
                text: 'Live random data'
            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150,
                maxZoom: 20 * 1000
            },
            yAxis: {
                minPadding: 0.2,
                maxPadding: 0.2,
                title: {
                    text: 'Value',
                    margin: 80
                }
            },
            series: [{
                name: 'Random data',
                data: [1]
            }]
        });
    });
    </script>

</head>
<body>

    <!-- 3. Add the container -->
    <div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>

我的服务器应按要求提供json编码字符串。
func main(){
http.HandleFunc("/",foo)
http.ListenAndServe(":3000", nil)
}
func foo(w http.ResponseWriter, r *http.Request) {
numbers := []int{14,5}
js, err := json.Marshal(numbers)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("Received Request")
w.Header().Set("Content-Type", "text/json")
  w.Write(js)
}

我可以看到高图发出了请求。我猜是ajax调用不理解我的json吗?

感谢您的任何帮助:)

编辑:我是否也做成功消息作为返回?

最佳答案

错误(表示@jmaloney的提示)

{"readyState":4,"status":200,"statusText":"success"}
ajax.html:28 parsererror: Error: jQuery110109016359453089535_1446814074235 was not called

一个简单的
w.Header().Set("Access-Control-Allow-Origin", "*")

在我的服务器上解决了:)

关于javascript - Golang Highcharts动态数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33550607/

10-09 23:06