jquery工具叠加:根据ajax响应打开叠加层

时间:2011-09-02 05:52:38

标签: jquery overlay jquery-tools

我正试图在按钮点击上打开叠加层。该按钮与ajax调用相关联,如果返回错误,则应打开覆盖,但成功时覆盖不会打开。

无论ajax响应中的成功/错误如何,覆盖都会打开。它会在按钮单击时打开,而不是在ajax响应上打开。我在这里想念的是什么?

这是我正在尝试的......

//Overlay setup
$('#PostQuestion').overlay({
    target: "#template"
});

//Ajax call setup
$('#PostQuestion').click(function() {
    $.ajax({
        url: '/ask_away',
        dataType: "json",
        data: {question: 'something'},
        type: 'POST',
        cache: false,
        success: function(response) {
            alert("It was a success");
        },
        error: function(request, error) {
            $('#PostQuestion').data('overlay').load();
        }
    });
});

<!-- HTML Here -->
<div id="template">You got an error</div>
<div id="PostQuestion">Ask Question</div>

1 个答案:

答案 0 :(得分:1)

叠加显示ajax调用成功/错误的原因是因为:

$('#PostQuestion').overlay({
    target: "#template"
});

基本上定义#PostQuestion div的点击处理程序以打开叠加层。因此,一旦你点击PostQuestion div,你不仅发送了ajax而且还显示了叠加层(就像我上面说的代码片段的结果一样)。

要使其按预期工作,请检查以下代码。还有一个简单的注意事项 - 即使ajax调用返回200 OK,但不是正确的json数据,也会使用错误处理程序,因此在开发过程中请记住这一点。

$(function() {
            //Overlay setup
            //select the overlay element in the jQuery selector and not the trigger element
            $("#template").overlay();

            //Ajax call setup
            $('#PostQuestion').click(function() {
                $.ajax({
                    url: '/ask_away',
                    dataType: "json",
                    data: {question: 'something'},
                    type: 'POST',
                    cache: false,
                    success: function(response) {
                        alert("It was a success");
                    },
                    error: function(request, error) {
                        $("#template").data('overlay').load();
                    }
                });
            });
        })