【发布时间】:2014-07-02 12:26:32
【问题描述】:
我可以在另一个域中使用 JSON 值绘制图表。我使用 ajax 和回调来进行跨域并获取值。
function drawChart() {
var options = {
chart: {
renderTo: 'chart01',
marginRight: 0,
marginTop: 60,
type: 'column',
options3d: {
enabled: true,
alpha: 15,
beta: 15,
viewDistance: 25,
depth: 90
}
},
plotOptions: {
column: {
depth: 90
}
},
title: {
text: 'CSV Values'
},
xAxis: {
title: {
text: '',
margin: 0
},
categories: []
},
yAxis: {
title: {
text: 'Title'
},
},
tooltip: {
enabled: false
},
series: []
};
$.ajax({
url: "http://<external_path>/json.asp?callback=?",
data: 'show=impression',
type: 'post',
dataType: "json",
success: function (data) {
var intSeries = data.length;
var cont = 0;
if (intSeries > 0) {
intSeries--;
options.xAxis.categories = data[cont]['data'];
while (cont < intSeries) {
options.series[cont] = data[cont + 1];
cont++;
}
var chart = new Highcharts.Chart(options);
}
}
});
};
在json.asp(在另一台服务器中)我返回带有回调的 json 值:
Response.ContentType = "application/json"
dim strJSON
strJSON = "" & _
"[" & _
"{" & _
"""name"": ""General Values""," & _
"""data"": [""Porcentaje""]" & _
"}, {" & _
"""name"": ""Value 1""," & _
"""data"": [34.60436]" & _
"}, {" & _
"""name"": ""Value 2""," & _
"""data"": [12.30343]" & _
"}, {" & _
"""name"": ""Value 3""," & _
"""data"": [53.30423]" & _
"}" & _
"]"
response.write request.QueryString("callback") & "(" & strJSON2 & ")"
它工作正常。我的问题是使用外部 CSV 或 XML 运行图表。我已经证明了一些方法,但我总是收到错误 401 Unauthorized。我从dataType: "json" 更改为dataType: "text" 或dataType: "xml"(CSV 和XML 模式),并使用新的外部路径,但它不起作用。
如何从外部 CSV 或 XML 文件中获取值?我无法将这些文件放在我的服务器上,所以我需要它在另一台服务器上。
更新: 我在我的服务器上添加了使用以下值启用 CORS:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: *
并且我已经修改了 ajax 方法:
$.ajax({
url: "http://<external_path>/test.csv",
type: 'post',
dataType: "text",
xhrFields: {
withCredentials: true
}
//-- I've tried to authenticate without success
//beforeSend: function (request){ request.setRequestHeader( ""Authorization"", btoa('<user>:<pass>')); },
success: function (data) {
//---- Code to get values ----//
}
});
更改后,我继续出现 401 错误。
【问题讨论】:
-
您是否在外部服务器上设置了 CORS?允许来自不同域的流量和 AJAX 请求。
-
我会尝试设置启用...
-
所以你有授权。您是否随请求一起传递了凭据?
标签: javascript json csv asp-classic highcharts