Home > Mobile >  How can I implement the Ajax error function?
How can I implement the Ajax error function?

Time:08-10

This is my app.py code:

@app.route('/index', methods=['GET', 'POST'])
def test_post():
    theName=request.form['name']
    theAge=request.form['age']
    if theName and theAge:
        return jsonify({'output':'Your name is ' theName ' , and your age is ' theAge ' , right?'})
    return jsonify({'error': 'Missing Data!'}) 

This is my index.html code about Ajax:

<script>
    $(document).ready(function () {
        $('#form').on('submit', function (e) {
            $.ajax({
                data: {
                    name: $('#name').val(),
                    age: $('#age').val(),
                },
                type: 'POST',
                url: '/index'
            })
                .done(function (data) {
                    $('#output').text(data.output).show();
                });
            e.preventDefault();
        });
    });
</script>

I want to know, if the entered name and age are empty, how can the returned 'Missing Data!' on the page. Thanks for your help very much!

CodePudding user response:

You just have to paste this in your .data function,

.done(function(data){

 if(data.error == "Missing Data!"){
          alert("Missing Data");
     }else{
          $("#output").text(data.output);
     }

Hope this works fine for you

  •  Tags:  
  • ajax
  • Related