我正在编写一个代码块,如果选中一个复选框,该代码块将触发一个 API。我已经测试了 API,它可以工作。在将表单变成小部件之前,我已经让表单发挥了作用。 (至少我认为我做到了?)
所以这是在检查时不会获取表单值的脚本:
<script type="text/javascript">
(jQuery || $)(function($) {
$('#survessay-form').on('submit', function() {
// the jquery element of the form
var $this = $(this);
if($this.find('input[type="checkbox"]').is('checked')) {
$.ajax({
type: "GET",
url: `https://www.example.com/?cmd=api-co-reg&apik=ukp!BjItWgMi6Qk&Email=${$('#awf_field-95505011').val()}&FirstName=${$('#awf_field-95505010').val()}&aff_sid=emailcoreg&cmp=1320&cxid=242570`
}).done(function(data) {
data = data.result;
$("#checkedmessage").html("<p>Thanks, " + data.name + ", you're now a Swagbucks participant!</p>");
// continue to the confirmation page
}).fail(function(data) {
// verify data
data = data.responseJSON;
$("#errormessage").html("Error: Please check the format of your input");
});
}
// stops probagation of event (doesn't submit the request to the php page)
return false;
});
});
因此,这应该在选中复选框并且用户单击提交按钮时提交 API,但它会继续执行表单操作方法。无需提交请求。我在这里缺少什么?
最佳答案
如果版本早于1.9.0,请使用类型:GET。否则使用方法:GET。此外,您的 URL 应该以 "开头和结尾,而不是单引号,因为您的某些参数值具有单引号。下面是代码的编辑版本。尝试使用浏览器开发人员工具来调试您的代码。
(function($) {
$('#survessay-form').on('submit', function() {
// the jquery element of the form
var $this = $(this);
if($this.find('input[type="checkbox"]').is('checked')) {
$.ajax({
method: "GET",
url: "https://www.example.com/?cmd=api-co-reg&apik=ukp!BjItWgMi6Qk&Email=" + $('#awf_field-95505011').val() + "&FirstName=" + $('#awf_field-95505010').val() + "&aff_sid=emailcoreg&cmp=1320&cxid=242570",
success: function(data) {
data = data.result;
$("#checkedmessage").html("<p>Thanks, " + data.name + ", you're now a Swagbucks participant!</p>");
// continue to the confirmation page
}
}).fail(function(data) {
// verify data
data = data.responseJSON;
$("#errormessage").html("Error: Please check the format of your input");
}
// stops probagation of event (doesn't submit the request to the php page)
return false;
});
})(jQuery);
关于php - 使用 GET 的 AJAX API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48770059/