태그 보관물: jsonp

jsonp

getJSON 호출에서 오류 처리 jsonp를 사용하여 도메인 간

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 요청을 수행하는 동안 오류 및 시간 초과를 추적하는 방법을 찾는 사람에게 도움이 될 것이라고 생각합니다. 따라서 질문에 대한 내 대답 아래

getJSON 구조는 다음과 같습니다 ( http://api.jqueri.com에 있음 ).

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

대부분의 사람들은

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

여기서 url var를 사용하여 JSON 데이터에 대한 링크를 제공하고 datatosend "?callback=?"는 올바른 JSON 데이터를 리턴하기 위해 전송해야하는 변수 및 기타 변수 를 추가하고 데이터 처리를위한 함수로서 성공 함수를 추가합니다. .

그러나 성공 함수에 status 및 xhr 변수를 추가 할 수 있습니다. 상태 변수에는 “성공”, “수정되지 않음”, “오류”, “시간 초과”또는 “파서 오류”문자열 중 하나가 포함되며 xhr 변수에는 반환 된 XMLHttpRequest 객체 ( 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");
    }
});

이렇게하면 요청이 완료되면 시작되는 사용자 지정 시간 초과 추적기를 구현하지 않고도 시간 초과 및 오류를 쉽게 추적 할 수 있습니다.

이것이 여전히 누군가이 질문에 대한 답을 찾는 데 도움이되기를 바랍니다.


답변

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

jQuery 2.x에서 수정되었습니다. jQuery 1.x에서는 오류 콜백이 발생하지 않습니다.


답변

나는이 같은 문제에 직면했지만 실패한 요청에 대한 콜백을 생성하는 대신 json 데이터 객체에 오류를 반환했습니다.

가능하다면 가장 쉬운 해결책 인 것 같습니다. 다음은 내가 사용한 Python 코드 샘플입니다. (Flask, Flask의 jsonify f 및 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.")

그런 다음 Javascript를 다음과 같이 확인할 수 있습니다.

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

답변

왜 안돼?

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

??

사용 된 .fail()방법 (jQuery 1.5 이상) 에 대한 자세한 내용 은 http://api.jquery.com/jQuery.ajax/#jqXHR을 참조하십시오.

jqXHR는 함수에 의해 반환 되므로 체인과 같은

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

가능합니다.