php - 使用 GET 的 AJAX API

标签 php jquery ajax

我正在编写一个代码块,如果选中一个复选框,该代码块将触发一个 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/

相关文章:

javascript - 使用 AJAX Jquery Javascript 单击函数

javascript - 使用 Javascript、AJAX、PHP、MySql 构建公共(public)聊天室时出现问题

jquery - 在 jQuery 的 ajax 成功回调中初始化 Angular 应用程序

PHP PDO fetch 返回一个数组?

php - Amazon S3 - 您建议的上传小于允许的最小大小

javascript - 相关下拉元素上的 if-else 语句的问题

javascript - html margin 问题 - "Shaking"网站

javascript - 制作背景图片链接

javascript - PHP 需要输出 ' 而不是 '

PHP 的 error_log() 与 syslog()