【问题标题】:How to use jquery when on post with success callback发布成功回调时如何使用jquery
【发布时间】:2016-02-06 16:08:37
【问题描述】:

我有一个应用程序需要三个不同的发布请求来同步数据,我只希望在所有三个完成时发生一件事,但 jquery 何时不工作。所有帖子都使用成功函数来处理服务器发回的数据。这是我的代码:

var picUploads = $.post("http://www.epcmapp.co.za/php2/uploadPic.php", {Images: jsonPics}, function (res) {
    alert("Ajax Images return");    
    if(res != "" && res != "53554343455353")
        alert(res);
});

var pdfUploads = $.post("http://www.epcmapp.co.za/php2/uploadPDF.php", {PDFs: jsonPDF}, function (res) {
    alert("Ajax PDF return");        
    if(res != "" && res != "53554343455353")
        alert(res);
});

var sync = $.post("http://www.epcmapp.co.za/php2/sync.php", {data: json}, function (res) {
    alert("Ajax return");    
    var result = JSON.parse(res);    
    dropSyncTables();
    checkDB();
    for (var i in result) {
        populateDB(result[i].toString());
    }
    readDB();    

    loadProjects();
    loadAdditional();
    loadProcessRows();
    loadAttachments();                                
});

$.when(picUploads, pdfUploads, sync).then(function() {
    $("#loadIcn").attr("src", "images/check3.png");
});

帖子中的警报不会弹出,jquery 中的代码也不会运行。那我该怎么做呢?

【问题讨论】:

  • 你排除了ajax调用失败的可能性吗?
  • 在您的then 中添加一个错误处理程序,看看您的延迟处理程序是否失败。
  • $.when(picUploads, pdfUploads, sync).then(function() 是否被调用?
  • 控制台说明了什么?

标签: javascript jquery ajax


【解决方案1】:

如果需要失败函数,则不能使用 $.get 或 $.post 函数;您将需要直接调用 $.ajax 函数。你传递了一个可以有“成功”和“错误”回调的选项对象。

而不是这个:

$.post("/post/url.php", parameters, successFunction);

你会用这个:

$.ajax({
    url: "/post/url.php",
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction
});

还有很多其他选项可用。该文档列出了所有可用选项。
ref This answer

【讨论】:

    【解决方案2】:

    首先检查您的console.log。你可能会在那里找到问题。但即使你找到它,你也总是需要某种错误处理,这对于延迟对象是可能的:

    $.when(picUploads, pdfUploads, sync)
        .then(function() {
            $("#loadIcn").attr("src", "images/check3.png");
        })
        .fail(function(ts) {
            alert('something failed');
            console.log(ts.responseText); //Check in console what went wrong here
        })
    

    还可以将done()fail()$.post 一起使用(从jQuery 1.5 开始)

    var picUploads = $.post("http://www.epcmapp.co.za/php2/uploadPic.php", {Images: jsonPics}, function (res) {
        alert("Ajax Images return");    
        if(res != "" && res != "53554343455353")
            alert(res);
    })
    .done(function() {
      alert( "second success" );
    })
    .fail(function() {
      alert( "error" );
    });
    

    【讨论】:

    • 我在 ipad 中测试了基于 Web 的应用程序,但看不到控制台错误,但是在我更改了一些代码以在浏览器中对其进行测试后,控制台错误只是尝试使用非全局变量呵呵
    • 很高兴能为您提供帮助!
    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 2019-11-12
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多