我正在尝试按照他们的规定创建表单,但我在表单字段的谷歌表格中未定义。这是我的代码
var $form = $('form#test-form'),
url = 'https://script.google.com/macros/s/AKfycbxLarVG8hcqD6DTXAd5FITK9lZhy_zF-DsBtEVCdAOfah5yT04/exec'
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(
// do something
);
})
<div>
<label>Field 1</label>
<input type="text" name="form_field_1" placeholder="Field 1"/>
</div>
<div>
<label>Field 2</label>
<input type="text" name="form_field_2" placeholder="Field 2"/>
</div>
<div>
<label>Field 3</label>
<input type="text" name="form_field_3" placeholder="Field 3"/>
</div>
<div>
<label>Field 4</label>
<input type="text" name="form_field_4" placeholder="Field 4"/>
</div>
<div>
<button type="submit"id="submit-form">Submit</button>
</div>
</form>
最佳答案
我不知道您是否错过了仅在这篇文章中包含 JQuery 库,但这是您的问题之一。首先,引用 Jquery 库,如下所示:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
当您这样做时,您会收到一条错误消息,指出 SerializeObject 不是函数。同样,您可以使用创建该函数的外部库或编写自己的函数,如下所示:
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
顺便感谢@ravi_kant_dubey 编写了这个函数,您可以从 here 看到该主题.
最后用该代码做一些事情,看看一切是否正常。
function(e){console.log(e);}
Anyway, if you run the script below, you can see that the response returns without any problems. Which means that it is working.
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var $form = $('form#test-form'),
url = 'https://script.google.com/macros/s/AKfycbxLarVG8hcqD6DTXAd5FITK9lZhy_zF-DsBtEVCdAOfah5yT04/exec'
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(function(e){console.log(e);}
// do something
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Field 1</label>
<input type="text" name="form_field_1" placeholder="Field 1"/>
</div>
<div>
<label>Field 2</label>
<input type="text" name="form_field_2" placeholder="Field 2"/>
</div>
<div>
<label>Field 3</label>
<input type="text" name="form_field_3" placeholder="Field 3"/>
</div>
<div>
<label>Field 4</label>
<input type="text" name="form_field_4" placeholder="Field 4"/>
</div>
<div>
<button type="submit"id="submit-form">Submit</button>
</div>
</form>
关于javascript - 如何在不使用 Google Forms 的情况下将 HTML 表单提交到 Google Sheets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938693/