简体   繁体   English

如何将 Ajax 中的数组值插入 Google App 脚本电子表格

[英]How to Insert Array Value from Ajax into Google App Script Spreadsheet

I create form in my Wordpress Website.我在我的 Wordpress 网站中创建表单。

And then, I'm using bootstrap multiselect to make many checkbox inside select option field.然后,我使用引导多选在 select 选项字段中制作许多复选框。 So yeah, I put like wp_enqueue_script and style for bootstrap multiselect.所以,是的,我把 wp_enqueue_script 和样式用于引导多选。 Working good.工作很好。

Actually, the data can still added but only one value that inserted into spreadsheet.实际上,数据仍然可以添加,但只有一个值插入到电子表格中。

That means, only index of 0 that inserted into spreadsheet.这意味着,只有 0 的索引插入到电子表格中。 I want all of value that user checked inside one cell.我想要用户在一个单元格内检查的所有值。

I'm already experiment for hours, but still not fixed.我已经试验了几个小时,但仍未修复。 I'm already using join(", ") so maybe I all value can inserted using comma separated value (not working).我已经在使用 join(", ") 所以也许我所有的值都可以使用逗号分隔值插入(不起作用)。 Oh, maybe I'm using $.each() and append(), still not working.哦,也许我正在使用 $.each() 和 append(),但仍然无法正常工作。

Here is my code:这是我的代码:

    <form class="nus-event-form">
    <div class="nus-event-form-container"> <div id="nus_event_form_alerts"></div>
    <div class="nus-event-form-content">
                            <select name="facultyInterest" class="facultyInterest" id="facultyInterest" class="multiselect" multiple="multiple">
                                <option value="College of Design and Engineering">College of Design and Engineering</option>
                                <option value="Faculty of Arts and Social Sciences">Faculty of Arts and Social Sciences</option>
                                <option value="Faculty of Dentistry">Faculty of Dentistry</option>
                                <option value="Faculty of Law">Faculty of Law</option>
                                <option value="Faculty of Science">Faculty of Science</option>
                                <option value="Institute of Systems Science">Institute of Systems Science</option>
                                <br /><br />
                            </select>
                        </div>
    <div class="nus-event-form-submit">
                                <input type="submit" name="submit" class="nus-event-submit-btn" id="submitBtn" style="color: white">
                                <div class="btnwrap">
                                    <button type="button" id="loadingBtn" class="u-btn">
                                        <div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
                                    </button>
                                </div>
                        </div>
    
    </div>
</form>

and then this is my ajax javascript:然后这是我的 ajax javascript:

$(document).ready(function(){
           
            $('#facultyInterest').multiselect({
                includeSelectAllOption: true,
                nonSelectedText:'School/Faculty/College of interest'
            });

            $('.nus-event-form').validate({
                ignore: [],
                rules:{
                    facultyInterest: "required"
                },
                messages:{
                    facultyInterest:{
                        required: 'Mohon masukkan sekolah/fakultas/kampus yang diminati!'
                    }
                },
                errorPlacement: function(error, element) {
                    if (element.hasClass('multiselect')) {
                        error.insertAfter(element.next('.btn-group'))
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(){
             
                    var data = $('.nus-event-form').serializeArray();
         
                    $.ajax({
                        url: 'https://script.google.com/macros/s/key/exec',
                        data: data,
                        type: 'POST',
                        success: function(response){
                            $("#submitBtn").css("display", "none");
                            $("#loadingBtn").css("display", "block");
                            
                            var json = JSON.stringify(response.result);
                            
                            setTimeout( () => {
                                $("#submitBtn").css("display", "block");
                                $("#loadingBtn").css("display", "none");

                                if(json.slice(1, -1) == "success"){
                                    $("#nus_event_form_alerts").html("<div class='alert alert-success'>Terima kasih! Formulir Anda sudah diterima dan akan di follow up dalam waktu 24 jam.</div>");
                                    $(".nus-event-form")[0].reset();
                                }else{
                                    $("#nus_event_form_alerts").html("<div class='alert alert-danger'>Formulir gagal diterima!</div>")
                                }
                            }, 5000);
                        }
                    });
                }
            });


        });

this is my app script code:这是我的应用脚本代码:

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow() + 1

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

I hope I can get the help, I'm really frustrated because the code not working to what I want.我希望我能得到帮助,我真的很沮丧,因为代码没有达到我想要的效果。 Thank you developers.感谢开发者。

update:更新:

I insert this code:我插入这段代码:

var data = $('.nus-event-form').serializeArray().map((e)=>{
                        return e.value;
                    }).join(', ');

But I don't understand why still not inserted inside google spreadsheet.但我不明白为什么仍然没有插入谷歌电子表格中。

I'm already fixing the code.我已经在修复代码了。 For developers that have same problem like mine, you can check this url: Using select multiple to send multiple values to google sheets using google apps script对于像我一样有同样问题的开发人员,您可以查看此 url: 使用 select multiple to send multiple values to google sheet using google apps script

So, the problem is from App Scripts code.所以,问题出在 App Scripts 代码上。

My code like this before:我之前的代码是这样的:

return header === 'timestamp' ? new Date() : e.parameter[header]

And then, I just add join functions: join();然后,我只添加连接函数:join();

return header === 'timestamp' ? new Date() : e.parameters[header].join(",");

Here is my full apps script code:这是我的完整应用程序脚本代码:

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow() + 1

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameters[header].join(",");
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

After that, in your javascript using serialize();之后,在您的 javascript 中使用 serialize();

Here is my full code:这是我的完整代码:

submitHandler: function(){
             
                    var data = $('.nus-event-form').serialize();
             
                    $.ajax({
                        url: 'https://script.google.com/macros/s/key/exec',
                        data: data,
                        type: 'POST',
                        success: function(response){
                            $("#submitBtn").css("display", "none");
                            $("#loadingBtn").css("display", "block");
                            
                            var json = JSON.stringify(response.result);
                            
                            setTimeout( () => {
                                $("#submitBtn").css("display", "block");
                                $("#loadingBtn").css("display", "none");

                                if(json.slice(1, -1) == "success"){
                                    $("#nus_event_form_alerts").html("<div class='alert alert-success'>Anda telah berhasil mendaftar untuk Event NUS Postgraduate by Coursework Fair 2022 (PGCF 2022). Silahkan cek Email Anda! Kami akan mengirimkan pengingat dan pembaruan menjelang acara dan detail login Anda satu hari sebelum acara (yaitu 3 Okt 2022).</div>");
                                    $(".nus-event-form")[0].reset();
                                }else{
                                    $("#nus_event_form_alerts").html("<div class='alert alert-danger'>Formulir gagal diterima!</div>")
                                }
                            }, 5000);
                        }
                    });
                }

Happy coding!快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM