![](/img/trans.png)
[英]Why won't my $.ajax call return a json object from a cshtml file?
[英]Why is JSON Object for Ajax throwing an error, but json file doesn't?
我嘗試將 JSON object 顯示在谷歌圖表中。
當我在 ajax 中調用 json 文件時,我可以顯示谷歌圖表,但是當我嘗試從代碼隱藏中獲取數據時,出現錯誤。
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetData()
{
var chartData = new object[10+ 1];
int j = 0;
for (int i=1; i <= 10; i++)
{
chartData[j] = new object[] { i.ToString(), i*i, i};
j++;
}
//return chartData;
string json = JsonConvert.SerializeObject(chartData);
return json;
}
根據 json 格式化程序,我在這里得到的 Json 字符串是有效的。 "[[\"1\",1,1],[\"2\",4,2],[\"3\",9,3],[\"4\",16,4], [\"5\",25,5],[\"6\",36,6],[\"7\",49,7],[\"8\",64,8],[\ "9\",81,9],[\"10\",100,10]]"
所以我有字符串,數字,數字作為數組。
我的電話看起來像這樣(我從https://www.encodedna.com/google-chart/create-line-charts-with-dynamic-json-data-using-google-charts.htm得到它),這很好用如果我使用 json 文件作為數據,當我嘗試使用它后面的代碼中的數據時會跳轉到錯誤中:
<script>
// Visualization API with the 'corechart' package. url: "data.json",
google.charts.load('visualization', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
$.ajax({
url: "Chart.aspx/GetData",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrSales = [['RejectReason', 'Count', 'Perc. (%)']]; // Define an array and assign columns for the chart.
// Loop through each data and populate the array.
$.each(data, function (index, value) {
arrSales.push([value.RejectReason, value.Count, value.Perc]);
});
// Set chart Options.
var options = {
title: 'Sorting',
curveType: 'function',
legend: { position: 'bottom', textStyle: { color: '#555', fontSize: 14 } } // You can position the legend on 'top' or at the 'bottom'.
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(arrSales)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(figures, options); // Draw the chart with Options.
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
我希望后面的代碼顯示在谷歌圖表中。 后來我想使用從數據庫中提取和豐富的數據來顯示,所以我不會從 json 文件中訪問它。
這是錯誤的 JSON 數據
您應該避免 JSON 字符串中的"
和\
[[1,1,1],[2,4,2],[3,9,3],[4,16,4],[5,25,5],[6,36,6],[7,49,7],[8,64,8],[9,81,9],[10,100,10]]
您可以使用從 JSON 格式化程序復制的代碼,它僅供查看。 您的 JSON 文件包含正確的 JSON。 我認為這不是人類可讀的格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.