IT story

getJSON 호출에서 오류 처리

hot-time 2020. 5. 17. 10:42
반응형

getJSON 호출에서 오류 처리


getJSON 호출에서 오류를 어떻게 처리 할 수 ​​있습니까? jsonp를 사용하여 도메인 간 스크립트 서비스를 참조하려고하는데 오류 방법을 어떻게 등록합니까?


$.getJSON() JSON 인코딩 응답을 원한다는 것을 알려주는 일반적인 AJAX 호출의 추상화입니다.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

일반적으로 (실제로 호출하기 전에 AJAX 호출을 구성하여) 또는 구체적으로 (메소드 체인 사용) 두 가지 방법으로 오류를 처리 할 수 ​​있습니다.

'일반'은 다음과 같습니다.

$.ajaxSetup({
      "error":function() { alert("error");  }
});

그리고 '구체적인'방법 :

$.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

누군가 Luciano에게 다음과 같은 점을 알려줍니다.) 방금 그의 대답을 테스트했습니다-비슷한 질문이 있었고 완벽하게 작동했습니다 ...

나는 심지어 50 센트를 추가합니다 :

.error(function(jqXHR, textStatus, errorThrown) {
        console.log("error " + textStatus);
        console.log("incoming Text " + jqXHR.responseText);
    })

여기 제가 추가했습니다.

에서 http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html공식 소스

" jQuery 1.5에 도입 된 jqXHR.success (), jqXHR.error () 및 jqXHR.complete () 콜백 메소드는 jQuery 1.8에서 더 이상 사용되지 않습니다. 최종 제거를 위해 코드를 준비하려면 jqXHR.done (), jqXHR을 사용하십시오. .fail () 및 jqXHR.always () 대신 "

나는 그것을했고 여기 Luciano의 업데이트 된 코드 스 니펫이 있습니다.

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });

그리고 오류 설명과 함께 모든 JSON 데이터를 문자열로 표시합니다.

$.getJSON("example.json", function(data) {
  alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });

경고가 마음에 들지 않으면 console.log

$.getJSON("example.json", function(data) {
  console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });

나는 누군가가 여기에 대답하고 포스터가 이미 여기 또는 다른 곳에서 그의 대답을 얻은 지 오래 된 것을 알고 있습니다. 그러나이 게시물은 getJSON 요청을 수행하는 동안 오류 및 시간 초과를 추적하는 방법을 찾는 사람에게 도움이 될 것이라고 생각합니다. 따라서 질문에 대한 내 대답 아래

The getJSON structure is as follows (found on http://api.jqueri.com):

$(selector).getJSON(url,data,success(data,status,xhr))

most people implement that using

$.getJSON(url, datatosend, function(data){
    //do something with the data
});

where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.

You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object (found on w3schools)

$.getJSON(url, datatosend, function(data, status, xhr){
    if (status == "success"){
        //do something with the data
    }else if (status == "timeout"){
        alert("Something is wrong with the connection");
    }else if (status == "error" || status == "parsererror" ){
        alert("An error occured");
    }else{
        alert("datatosend did not change");
    }         
});

This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.

Hope this helps someone still looking for an answer to this question.


$.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })

It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback


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
    }
});

Why not

getJSON('get.php',{cmd:"1", typeID:$('#typesSelect')},function(data) {
    // ...
});

function getJSON(url,params,callback) {
    return $.getJSON(url,params,callback)
        .fail(function(jqXMLHttpRequest,textStatus,errorThrown) {
            console.dir(jqXMLHttpRequest);
            alert('Ajax data request failed: "'+textStatus+':'+errorThrown+'" - see javascript console for details.');
        })
}

??

For details on the used .fail() method (jQuery 1.5+), see http://api.jquery.com/jQuery.ajax/#jqXHR

Since the jqXHR is returned by the function, a chaining like

$.when(getJSON(...)).then(function() { ... });

is possible.


In some cases, you may run into a problem of synchronization with this method. I wrote the callback call inside a setTimeout function, and it worked synchronously just fine =)

E.G:

function obterJson(callback) {


    jqxhr = $.getJSON(window.location.href + "js/data.json", function(data) {

    setTimeout(function(){
        callback(data);
    },0);
}

참고URL : https://stackoverflow.com/questions/1740218/error-handling-in-getjson-calls

반응형