将JSON传递给JQuery函数Javascript [英] Pass JSON to JQuery function Javascript
问题描述
我们有一个非常简单的Google Apps脚本Web应用程序,目的是在HTML下拉列表中显示JSON数据。 JSON文件存在于Google云端硬盘中。灵感代码来自: http://jsfiddle.net/manoj_admlab/Mta5b/3/
We have a very simpel Google Apps Script Web App, which purpose is to show JSON data in a HTML drop-down-list. The JSON file exists in Google Drive. Inspiration code from: http://jsfiddle.net/manoj_admlab/Mta5b/3/
但是,当我们尝试'取Json'时,没有数据被加载到下拉列表中:
But when we are trying to 'Fetch Json' no data is loaded in to the dropdown-list:
<!DOCTYPE html>
<html>
<br> <br>
<center>
<head>
<base target="_top">
</head>
<body>
<select id="destinations">
<option value="">Select</option>
</select>
<a href="#" id="fetch">Fetch JSON</a>
</center>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
google.script.run.getJson(); // Runs the function "getJson();" in Code.gs
$('#fetch').click(function(s) {
$.post(s, {json: JSON.stringify(json)}, function(data) {
$.each(data.Destinations, function(i, v) {
$('#destinations').append('<option value="' + v.destinationID + '">' + v.destinationName + '</option>');
});
});
});
</script>
</body>
</html>
Code.gs
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile('index');
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
function getJson() {
var files = DriveApp.getFilesByName("jsonData.json");
var file = files.next();
var JSONDATA = file.getAs("application/json").getDataAsString();
//JSONDATA = JSON.stringify(JSONDATA);
JSONDATA = JSON.parse(JSONDATA);
Logger.log(JSONDATA);
click(JSONDATA); // <-- Trying to pass this data to "$('#fetch').click(function(s) {"
}
jsonData.json
jsonData.json
{
"options": {
"Destinations": [
{
"destinationName": "London",
"destinationID": "lon"
},
{
"destinationName": "New York",
"destinationID": "nyc"
},
{
"destinationName": "Paris",
"destinationID": "par"
},
{
"destinationName": "Rome",
"destinationID": "rom"
}
]
}
}
推荐答案
您必须返回 getJson()
函数中的数据,并且在调用它时需要传递一个回调函数,其中 withSuccessHandler()
,例如:
You have to return the data in getJson()
function, and when calling it, you need to pass a callback, with withSuccessHandler()
, as such:
我n HTML:
in HTML:
function justLog(e){
console.log(e);
}
$('#fetch').click(function(s) {
google.script.run.withSuccessHandler(justLog).getJson(); // Runs the function "getJson();" in Code.gs
});
在code.gs中完成以下操作:
in code.gs, finish the function with:
return JSONDATA;
这篇关于将JSON传递给JQuery函数Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!