1

Situation:

  • I have a simple form and will call a .post()-call () instead of the actual submit.
  • The post works as such that it will post the request and receive a 200 (OK) status with the expected string in the response body (as can be seen in the Net-View of FireBug).

Question:

  • The anonymous function with the alert() is never executed. Why is that?

Notes:

  • I have inserted an alert to indicate when the method fires
  • fiddle-links for convenience below the code.

The Code:

Here is my form:

<form>
    <input type="submit" value="Submit" />
</form>

This was what I expected to work:

$(document).ready(function () {
    $('form').submit(function (e) {
        e.preventDefault();
        $.post('/echo/html/', {
            html: "<span>jsFiddle test return msg</span>",
            delay: 1
        }, function (data, textStatus, jqXHR) { 
            $('form').append(data); 
            alert("done"); // <----- THIS NEVER FIRES
        }, 'json');
    });
});

FIDDLE 1


This does neither work:

$(document).ready(function () {
    $('form').submit(function (e) {
        e.preventDefault();
        $.post('/echo/html/', {
            html: "<span>jsFiddle test return msg</span>",
            delay: 1
        }, null, 'json').done(function (data, textStatus, jqXHR) {
            $('form').append(data);
            alert("done"); // <----- THIS NEVER FIRES
        });
    });
});

FIDDLE 2


This will trigger the alert but data will be empty.

$(document).ready(function () {
    $('form').submit(function (e) {
        e.preventDefault();
        $.post('/echo/html/', {
            html: "<span>jsFiddle test return msg</span>",
            delay: 1,
            success: function (data, textStatus, jqXHR) {
                $('form').append(data); // <----- DATA IS UNDEFINED
                 alert("done");         // <----- THIS FIRES!
            }
        }, null, 'json');
    });
});

FIDDLE 3

4

1 回答 1

4

您将错误的数据类型设置为 json,服务器返回 html 类型的数据。顺便说一句,您不需要指定它:

dataType 类型:字符串 服务器预期的数据类型。默认值:智能猜测(xml、json、脚本、文本、html)。

http://jsfiddle.net/9NrL5/4/

$(document).ready(function () {
    $('form').submit(function (e) {
        e.preventDefault();
        $.post('/echo/html/', {
            html: "<span>jsFiddle test return msg</span>",
            delay: 1
        }, function (data, textStatus, jqXHR) {
            $('form').append(data);
            alert("done");
        });
    });
});
于 2013-06-02T22:14:51.267 回答