jQuery: running success in 1.3.2 but not in 1.4.2

2019-08-27 18:56发布

问题:

Nothing is wrong, as soon as i change the lib to 1.3.2 my on success stuff works just fine? How comes? Not even the alert with TEST appears..

Here's the code this is happening on:

function crop() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url:"functions.php?action=crop",
        data: 
        {
            x: $('#x').val(),y: $('#y').val(),w: $('#w').val(),
            h: $('#h').val(),fname:$('#fname').val(),fixed:fixed,
            sizew:sizew,sizeh:sizeh},
            success: function(response)
            {
                alert('TEST');
                if(!fixed) // Missing { }
                { 
                    $("#showPhoto").css({overflow:"auto"}); // Missing ;
                }
                $("#showPhoto").html(
                    $(document.createElement("img")).attr(
                        "src",response.filename)).show();

                $("#showPhoto").after("There you go...").show();
                $("#image").slideUp();
           },
          error:function(response) {
                   console.log('error: ', response);
               }
        });
    }

How can i make it to work with jquery 1.4.2 library?

回答1:

The JSON coming back isn't valid, the example you posted:

({"filename":"images\/profilePhoto\/thumbs\/1283596240.jpg"}) 

And the response I got in the page:

({"filename":"1283597560.jpg"})

Both aren't valid JSON, you need to remove the () wrapper on there. You can check your JSON response for validity here: http://www.jsonlint.com/

The 1.3.2 vs 1.4.2 difference is that in 1.4.0 jQuery added strict JSON checking, if it's not valid it'll fail (so it can take better advantage of browsers' native JSON parsers).

From the 1.4 release notes:

Strict JSON parsing, using native JSON.parse: (jQuery.ajax() Documentation, Commit 1, Commit 2, Commit 3)

jQuery 1.3 and earlier used JavaScript’s eval to evaluate incoming JSON. jQuery 1.4 uses the native JSON parser if available. It also validates incoming JSON for validity, so malformed JSON (for instance {foo: "bar"}) will be rejected by jQuery in jQuery.getJSON and when specifying “json” as the dataType of an Ajax request.