将JSON传递给JQuery函数Javascript

我们有一个非常简单的Google Apps脚本Web应用程序,其目的是在HTML下拉列表中显示JSON数据。 JSON文件存在于Google云端硬盘中。 灵感代码来自: http : //jsfiddle.net/manoj_admlab/Mta5b/3/

但是当我们尝试“获取Json”时,没有数据被加载到下拉列表中: 在此处输入图像描述

的index.html

  

Select Fetch JSON 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('' + v.destinationName + ''); }); }); });

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

 { "options": { "Destinations": [ { "destinationName": "London", "destinationID": "lon" }, { "destinationName": "New York", "destinationID": "nyc" }, { "destinationName": "Paris", "destinationID": "par" }, { "destinationName": "Rome", "destinationID": "rom" } ] } } 

您必须在getJson()函数中返回数据,并且在调用它时,您需要使用withSuccessHandler()传递回调,如下所示:

在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中,用以下内容完成该function:

 return JSONDATA; 

谢谢Kriggs! 这很好:

index.html的:

         

Code.gs:

 function doGet() { return HtmlService.createHtmlOutputFromFile('Index') .setSandboxMode(HtmlService.SandboxMode.IFRAME); } function jsonData() { var a = { Cars: [{ "CarType": "BMW", "carID": "bmw123" }, { "CarType": "mercedes", "carID": "merc123" }, { "CarType": "volvo", "carID": "vol123r" }, { "CarType": "ford", "carID": "ford123" }] }; Logger.log(a); return a; }