Error handling in getJSON calls

后端 未结 9 1636
野的像风
野的像风 2020-11-28 02:09

How can you handle errors in a getJSON call? Im trying to reference a cross-domain script service using jsonp, how do you register an error method?

9条回答
  •  春和景丽
    2020-11-28 02:23

    I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.

    If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)

    try:
        snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
        db.session.delete(snip)
        db.session.commit()
        return jsonify(success=True)
    except Exception, e:
        logging.debug(e)
        return jsonify(error="Sorry, we couldn't delete that clip.")
    

    Then you can check on Javascript like this;

    $.getJSON('/ajax/deleteSnip/' + data_id,
        function(data){
        console.log(data);
        if (data.success === true) {
           console.log("successfully deleted snip");
           $('.snippet[data-id="' + data_id + '"]').slideUp();
        }
        else {
           //only shows if the data object was returned
        }
    });
    

提交回复
热议问题