Should I write the conditional branch using Ajax results in done?

Asked 2 years ago, Updated 2 years ago, 83 views

I would like to display the results of the inspection with Ajax, but I would like to apply the conditions of the JavaScript switch statement based on the results from the server. Is the switch statement written in done?
I don't know how to connect the switch statement to the results from the server.

source code

$(function(){
    // ajax button click
    $('#ajax').on('click', function(){
        $.ajax({
            url: '/home',
            type: 'GET',
            data: { 
            }
        })
     // Invoked when aax request is successfully
        .done((data)=>{
            console.log("Success");
            console.log("formList:"+data);
            $('result').html(data);
            console.log(data);
        })
        .fail((data)=>{
      });
    });
});

javascript jquery ajax

2022-09-30 10:42

1 Answers

Yes, I'll write it in done.
The action given to done is
when aax request is successful. The action given to fail is
when aax request fails. The actions passed to always are performed whether the ajax request succeeds or fails.
For ajax, data contains the response content.

$.ajax({
            url: 'http://example.com/api/v1/event/?' + queryString,
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback'
        })
        .done(data,textStatus,xhr)=>{
            // success
            // For example, when the server returns a string similar to the following:
            // {
            //     "fooBars": [
            //         {"id":1, "name":"alice",
            //         {"id":2, "name":"bob"}
            //     ]
            // }
            let name = data.fooBars[0].name;//alice
        })
        .fail(xhr,textStatus,errorThrown)=>{
            // error
        })
        .always(arg1,textStatus,arg3)=>{
            // complete
        });

Supplemental


2022-09-30 10:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.