我目前正在学习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?
感谢您提前提供任何帮助:)
编辑:作为回归,我是否也要做成功的消息?
答案 0 :(得分:1)
错误(thx到@jmaloney的提示)
{"readyState":4,"status":200,"statusText":"success"}
ajax.html:28 parsererror: Error: jQuery110109016359453089535_1446814074235 was not called
一个简单的
w.Header().Set("Access-Control-Allow-Origin", "*")
在我的go-Server上解决了它:)