Nguồn dữ liệu là một dịch vụ web hỗ trợ giao thức Nguồn dữ liệu của công cụ biểu đồ. Bạn có thể gửi một truy vấn SQL đến một Nguồn dữ liệu và phản hồi lại, bạn sẽ nhận được một DataTable (Bảng dữ liệu) chứa thông tin thích hợp. Một số ví dụ về Nguồn dữ liệu bao gồm
Bảng tính Google và SalesForce.
Gửi yêu cầu
Cách gửi yêu cầu:
Tạo thực thể cho đối tượng Truy vấn bằng URL của Nguồn dữ liệu. URL phải cho biết dữ liệu nào đang được yêu cầu, theo cú pháp mà nguồn dữ liệu đó có thể hiểu.
Nếu muốn, hãy chỉ định các tuỳ chọn yêu cầu, chẳng hạn như phương thức gửi dưới dạng tham số thứ hai không bắt buộc trong hàm khởi tạo đối tượng Query (xem tham số opt_options của hàm khởi tạo Truy vấn để biết thông tin chi tiết):
Bạn có thể thêm một chuỗi ngôn ngữ truy vấn để sắp xếp hoặc lọc kết quả rồi gửi yêu cầu. Không bắt buộc phải có nguồn dữ liệu để hỗ trợ
ngôn ngữ truy vấn Nguồn dữ liệu của Công cụ biểu đồ. Nếu không hỗ trợ ngôn ngữ truy vấn thì Nguồn dữ liệu sẽ bỏ qua chuỗi truy vấn SQL nhưng vẫn trả về một DataTable. Ngôn ngữ truy vấn là một biến thể ngôn ngữ SQL; hãy đọc toàn bộ cú pháp ngôn ngữ truy vấn tại đây.
Gửi truy vấn, chỉ định một trình xử lý gọi lại sẽ được gọi khi nhận được phản hồi: xem phần tiếp theo để biết thông tin chi tiết.
Dưới đây là ví dụ về cách gửi yêu cầu dữ liệu trong một dải ô của Bảng tính Google. Để tìm hiểu cách lấy URL của một Bảng tính Google, hãy xem tại đây:
function initialize() {
var opts = {sendMethod: 'auto'};
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('http://spreadsheets.google.com?key=123AB&...', opts);
// Optional request to return only column C and the sum of column B, grouped by C members.
query.setQuery('select C, sum(B) group by C');
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
// Called when the query response is returned.
...
}
Nếu bạn đang gửi truy vấn từ trong Apps Script, hãy nhớ sử dụng chế độ IFRAME.
Xử lý phản hồi
Hàm trình xử lý phản hồi sẽ được gọi khi yêu cầu trả về. Tham số được chuyển vào hàm trình xử lý phản hồi thuộc loại google.visualization.QueryResponse.
Nếu yêu cầu thành công, phản hồi sẽ chứa một bảng dữ liệu (lớp google.visualization.DataTable). Nếu yêu cầu không thành công, phản hồi sẽ chứa thông tin về lỗi và không có DataTable.
Trình xử lý phản hồi của bạn cần làm như sau:
Kiểm tra xem yêu cầu thành công hay không thành công bằng cách gọi response.isError().
Bạn không cần phải hiển thị bất kỳ thông báo lỗi nào cho người dùng; Thư viện trực quan hoá sẽ
hiển thị thông báo lỗi cho bạn trong vùng chứa <div>. Tuy nhiên, nếu muốn xử lý lỗi theo cách thủ công, bạn có thể sử dụng lớp goog.visualization.errors để hiển thị thông báo tuỳ chỉnh (xem Ví dụ về Trình bao bọc truy vấn để biết ví dụ về cách xử lý lỗi tuỳ chỉnh).
Nếu yêu cầu thành công, phản hồi sẽ chứa DataTable mà bạn có thể truy xuất bằng cách gọi getDataTable(). Chuyển dữ liệu vào biểu đồ của bạn.
Mã sau đây minh hoạ cách xử lý yêu cầu trước đó để vẽ biểu đồ hình tròn:
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true});
}
Đọc tệp CSV
Nếu muốn tạo biểu đồ từ dữ liệu CSV (giá trị được phân tách bằng dấu phẩy), bạn có hai lựa chọn. Chuyển đổi dữ liệu CSV theo cách thủ công sang định dạng bảng dữ liệu của Google Biểu đồ hoặc đặt tệp CSV trên máy chủ web phân phát biểu đồ và truy vấn biểu đồ đó bằng kỹ thuật trên trang này.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2024-07-10 UTC."],[[["\u003cp\u003eThis page explains how to send a SQL query to a Datasource, a web service supporting the Chart Tools Datasource protocol, to receive a DataTable with the requested data.\u003c/p\u003e\n"],["\u003cp\u003eYou can use a Query object to send a request with optional parameters for sending method and a query language string for filtering data, receiving a response handled by a callback function.\u003c/p\u003e\n"],["\u003cp\u003eThe response handler checks for errors and, if successful, retrieves the DataTable from the QueryResponse for use in visualizations like charts.\u003c/p\u003e\n"],["\u003cp\u003eCSV data can be either manually converted to Google Charts datatable format or placed on a web server and queried using the techniques described on the page.\u003c/p\u003e\n"],["\u003cp\u003eMore detailed information on query language syntax, the Query class, and the QueryResponse class can be found via provided links.\u003c/p\u003e\n"]]],[],null,["# Data Queries\n\nThis page describes how to send a query to a data source that supports the Chart Tools Datasource\nprotocol.\n\nContents\n--------\n\n1. [Overview](#overview)\n2. [Sending a request](#Sending_a_Query)\n3. [Processing the response](#Processing_the_Query_Response)\n4. [Reading CSV files](#csv)\n5. [More information](#moreinfo)\n\nOverview\n--------\n\n\nA Datasource is a web service that supports the Chart Tools Datasource protocol. You can send a\nSQL query to a Datasource, and in response you will receive a DataTable populated with the\nappropriate information. Some examples of Datasources include\n[Google Spreadsheets](/chart/interactive/docs/spreadsheets) and SalesForce.\n\nSending a request\n-----------------\n\n**To send a request:**\n\n1. Instantiate a [Query](/chart/interactive/docs/reference#Query) object with the URL of your Datasource. The URL should indicate what data is being requested, in a syntax understood by that data source.\n2. Optionally specify request options such as sending method as an optional second parameter in the `Query` object constructor (see the Query constructor's [`opt_options`](/chart/interactive/docs/reference#Query) parameter for details):\n3. Optionally add a [query language string](/chart/interactive/docs/querylanguage) to sort or filter the results, and then send the request. Datasources are not required to support the Chart Tools Datasource query language. If the Datasource does not support the query language, it will ignore the SQL query string, but still return a `DataTable`. The query language is a SQL language variant; read the full [query language syntax here](/chart/interactive/docs/querylanguage).\n4. Send the query, specifying a callback handler that will be called when the response is received: see next section for details.\n\n\nHere's an example of sending a request for data in a Google Spreadsheet cell range; to learn how\nto get the URL for a Google Spreadsheet, see\n[here](/chart/interactive/docs/spreadsheets#Google_Spreadsheets_as_a_Data_Source): \n\n```gdscript\nfunction initialize() {\n var opts = {sendMethod: 'auto'};\n // Replace the data source URL on next line with your data source URL.\n var query = new google.visualization.Query('http://spreadsheets.google.com?key=123AB&...', opts);\n\n // Optional request to return only column C and the sum of column B, grouped by C members.\n query.setQuery('select C, sum(B) group by C');\n\n // Send the query with a callback function.\n query.send(handleQueryResponse);\n}\n\nfunction handleQueryResponse(response) {\n // Called when the query response is returned.\n ...\n}\n```\n\nIf you are sending your query from within Apps Script, be sure to use [`IFRAME` mode](/apps-script/reference/html/sandbox-mode).\n\nProcessing the response\n-----------------------\n\n\nYour response handler function will be called when the request returns. The parameter passed in\nto your response handler function is of type\n[google.visualization.QueryResponse](/chart/interactive/docs/reference#QueryResponse).\nIf the request was successful, the response contains a data table\n(class `google.visualization.DataTable`). If the request failed, the response contains\ninformation about the error, and no `DataTable`.\n\n**Your response handler should do the following:**\n\n1. Check whether the request succeeded or failed by calling `response.isError()`. You shouldn't need to display any error messages to the user; the Visualization library will display an error message for you in your container `\u003cdiv\u003e`. However, if you do want to handle errors manually, you can use the [`goog.visualization.errors`](/chart/interactive/docs/reference#errordisplay) class to display custom messages (see the [Query Wrapper Example](/chart/interactive/docs/examples#querywrapper) for an example of custom error handling).\n2. If the request succeeded, the response will include a `DataTable` that you can retrieve by calling `getDataTable()`. Pass it to your chart.\n\nThe following code demonstrates handling the previous request to draw a pie chart: \n\n```gdscript\nfunction handleQueryResponse(response) {\n\n if (response.isError()) {\n alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());\n return;\n }\n\n var data = response.getDataTable();\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, {width: 400, height: 240, is3D: true});\n}\n```\n\nReading CSV files\n-----------------\n\nIf you want to build a chart out of CSV (comma-separated values)\ndata, you have two choices. Either manually convert the CSV data into\nthe [Google\nCharts datatable format](/chart/interactive/docs/datatables_dataviews#creatingpopulating), or place the CSV file on the web server\nserving the chart, and query it using the technique on this page.\n\nMore information\n----------------\n\n- [Query Language Syntax](/chart/interactive/docs/querylanguage) - Describes the syntax of the language used to make data queries.\n- [Query Class](/chart/interactive/docs/reference#Query) - Reference page for the class that wraps a query.\n- [QueryResponse Class](/chart/interactive/docs/reference#QueryResponse) - Reference page for the class that wraps the response to a query."]]