【问题标题】:AJAX POST success and error firingAJAX POST 成功和错误触发
【发布时间】:2016-04-18 11:30:01
【问题描述】:

我在这里查看了很多关于同一问题的帖子,但没有任何效果,而且或多或少有点像一个小故障:

function onbtnclick(){


    var user_email=$('#user_email').val();
    var send_data = {email:user_email};

$.ajax({
        type: 'POST',
        url: 'someURL.php',
        crossDomain: true,
        data:send_data,
        dataType: 'text',
        success: function(responseData, textStatus, jqXHR) {
            alert("Thank you for the mailing list");
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('Your email is already in our mailing list.');
            console.log('log e:'+responseData);
            console.log('log e:'+textStatus);
            console.log('log e:'+errorThrown);
        }
    });

        return false;

 }
};


<form name="myform">
    <input  id="user_email" type="email" name="email" placeholder="Your Email Here" style="width:300px" required><br>
    <br><button type="submit" class="leka-button button-style2 offer_button" onclick="onbtnclick()"><h5>SIGN UP</h5></button>
</form>

如果用户新触发成功或者他注册触发错误,我只是试图提醒正确的消息,我尝试删除 dataType:'text' 或添加 'json' 并且\同时删除 crossDomain 属性但都没有给我理由。 如果这有用,here is where I fire the AJAX script.

【问题讨论】:

  • 常见错误:返回没有内容的错误200,导致错误。在 API 中返回代码 204(OK,无内容)。
  • @PierreEmmanuelLallemant 事实上,在成功事件中,我正在提醒 resposneData、textStatus、errorThrown 但它似乎甚至没有进入成功。
  • 运行这段代码会发生什么?成功功能会触发吗?错误函数会触发吗?回应是什么?抛出什么错误?
  • @Quentin 它将电子邮件注册到数据库中,并且不会触发任何成功或错误函数。我唯一的错误是: Uncaught TypeError: c.getAttribute is not a function 而且不确定它是否相关。

标签: javascript jquery ajax post


【解决方案1】:

点击提交按钮时调用 JavaScript。

JavaScript 运行。 Ajax 请求已准备就绪。 JavaScript 完成。提交按钮的默认行为是提交表单。页面卸载。 Ajax 请求已取消。进行常规表单提交。

去掉onclick 属性。改为使用 JavaScript 绑定您的事件处理程序。

$(function () {
    var $form = $([name="myform"]); // `name` is obsolete for form elements, give it an ID instead
    $form.on('submit', onbtnclick);

    function onbtnclick(event) { // Give this function a better name
        event.preventDefault(); // Don't submit the form normally
        // Then put the rest of your existing code
    }
});

【讨论】:

  • 给我一些逻辑,会尝试让你知道。
  • 不好意思问一下,先
    没问题,还是我把
  • @SadiqJaffer - 你去掉了 onclick 属性吗?这真的很重要。
  • 是的,我去掉了按钮的 onclick 属性。
  • 或者你可以简单地制作&lt;button type="button" - 这会做类似的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 2023-04-03
  • 2018-09-07
  • 1970-01-01
  • 2011-08-05
相关资源
最近更新 更多