javascript jQuery $.post 成功函数永远不会触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19322620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:09:41  来源:igfitidea点击:

jQuery $.post success function never fires

javascriptajaxjquery

提问by ProNotion

I have a $.post which using Fiddler I can see always posts successfully but my success function is never fired.

我有一个 $.post 使用 Fiddler 我可以看到总是成功发布但我的成功功能从未被触发。

A successful post to the url returns a 1 or failure returns a 0, on each occasion I have tested it returns the expected value of 1 so I'm at a lost as to what I'm doing wrong?

对 url 的成功发布返回 1 或失败返回 0,每次我测试它都会返回预期值 1,所以我不知道我做错了什么?

if ($('#mycheckbox').prop('checked')) {
    $.post('/base/MailingList/Subscribe/',
        {
            listId: $('#mycheckbox').val(),
            name: $('#subscriber-name').val(),
            email: $("#subscriber-email").val()
        },
        function(response) {
            console.log(response);
        });
}

回答by Zeke Alexandre Nierenberg

Stick another function as a final callback. That function will run in the failure case.

将另一个函数作为最终回调。该函数将在失败情况下运行。

The way jquery recommends doing it is this:

jquery 建议这样做的方式是这样的:

var jqxhr = $.post( "example.php", function() {
   alert( "success" );
})
.done(function() {
    alert( "second success" );
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
 });

回答by Jay

I'm not sure if this will help or not, but I always use fully qualified urls when I do any asynchronous calls. You may want to try:

我不确定这是否会有所帮助,但是当我执行任何异步调用时,我总是使用完全限定的 url。您可能想尝试:

$.post('http://mydomain.com/base/MailingList/Suscribe/', ...

Additionally, you will likely want your handling function to recieve all three argument from the callback (data, textStatus, jqXHR). This way, you can look at the txtStatus to verify if you have success or not.

此外,您可能希望处理函数从回调中接收所有三个参数(data、textStatus、jqXHR)。这样,您可以查看 txtStatus 以验证是否成功。

回答by Ivan Sokolov

In my case the problem was header with wrong MIME type ("application/json" instead of "text") in php file on server. If you send header that doesn't match type of data cause an error and $.post calls fail function.

在我的情况下,问题是服务器上的 php 文件中包含错误 MIME 类型(“application/json”而不是“text”)的标题。如果您发送与数据类型不匹配的标头会导致错误并且 $.post 调用失败函数。