jquery Ajax a problem with the pit daddy

Source: Internet
Author: User

Problem Description: jquery ajax datatype JSON, if the JSON data is not strict, do not enter the Success method, the console will not error.

Data.json

1 {"result": "0", "Data": 2016-04-27}

Ajax General Notation Code:

1 $.ajax ({2     URL: ' Data.json ',3     type: ' POST ',4     DataType: ' JSON ',5     function(data) {6         Console.log (data); 7     }8 });

The above code is probably the most common use of coder, if the server returned a data format such as Data.json, this code without any problems, the console also did not error, but will not execute the Success method (a small problem, it took half an hour to find out, I wonder if you crossing not stepped on this hole. If you call the JSON format method on this JSON data, you will get an error:

1 json.parse (' {' result ': ' 0 ', ' Data ': 2016-04-27} '); // Console Error: SyntaxError:JSON.parse:expected ', ' or '} ' after property value ' in ' Line 1 ' column ' of the JSON data 

Before encountering this problem, the small one also thinks that the error method is of no use, but if this code is added to the error method, it will prompt for errors:

1 $.ajax ({2URL: ' Data.json ',3Type: ' POST ',4DataType: ' JSON ',5Successfunction(data) {6Console.log (123);7     },8Errorfunction(){9Console.log ("Data Error");//Console output: "Data Error"Ten     } One});

Recommended Promise notation:

1 $.ajax ({2     URL: ' Data.json ',3     type: ' POST ',4     DataType: ' JSON '5 }). Done (function() {6     console.log ("Success") ); 7 }). Fail (function() {8     console.log ("error"); 9 });

Summary: After encountering this hole, tell the small one truth, the error method is necessary, although it seems to have no effect, but occasional error hints are necessary.

jquery Ajax a problem with the pit daddy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.