2014-07-21 1 views
2

나는 장바구니에 항목을 추가하는 jQuery 함수를 빌드하는 데 도움이되도록 http://api.jquery.com/jquery.post/을 사용했습니다.성공/실패를 jQuery/Ajax 함수에 포함하기

내 결과이이며 작동합니다

jQuery(document).ready(function() { 

// Attach a submit handler to the form 
$('form[name="cart_quantity"]').submit(function(event) { 

// Stop form from submitting normally and initiate function 
event.preventDefault(); 
return addtocart(jQuery(this)); 

}); // eof Attach a submit handler to the form 

// function 
function addtocart(thisForm) { 

// Get some values from elements on the page: 
$("#contentss").fadeIn("slow"); 
action = thisForm.attr("action"); 

// Send the data using post 
var posting = $.post(action, thisForm.serialize()); 

// Process post-results 
posting.done(function(data) { 

// find and put results in a div 
var shoppingCartSidebox = $(data).find('div#shoppingcart').html(); 
var numbernotify = $(data).find('div.numbernotify').html(); 
$('div#shoppingcartdiv').html(shoppingCartSidebox); 
$('div.numbernotify').html(numbernotify) 

// initiate slideDown/slideUp 
$(document.getElementById('contentss').style.display='none'); 
jQuery(document).ready(function() { 
$("#shoppingcartdiv").slideDown(); 
setTimeout(function() {$("#shoppingcartdiv").slideUp()}, 7000); 

}); // eof initiate slideDown/slideUp document ready 
}); // eof Process post-results 
} // eof function 
}); // eof main document ready 

나는 제품이 장바구니에 추가되지 않는 순간에 성공/실패 이벤트를 구현하고 싶습니다. 성공 이벤트는 이미 코딩되어 있으며 기본적으로 "// 결과 후 처리"이벤트 뒤에 정의됩니다.

그래서 성공과 비슷한 결과를 포함하는 실패 이벤트를 삽입해야합니다. 항목이 성공적으로 추가되었음을 사용자에게 경고하면 오류가 발생했다고 경고합니다. 그러나 나는 단지 물어보고 싶다. 예를 들어 사용자가 장바구니에 항목을 추가하는 동안 인터넷 연결이 끊어지는 경우와 같이 Fail 이벤트를 추가하는 경우 그것이 내가 본질적으로 찾고있는 것이기 때문에 ...

또한 나는 끔찍한 아마추어다고 생각하여 현재 코드와 개선 사항에 대한 조언을 매우 높이 평가할 것입니다.

+1

like posting.done (function (data) {}); posting.fail (function (data) {// 실패 할 경우}); posting.always (함수 (데이터) {성공 또는 실패 여부와 관계없이 항상 수행}); – Aman

+0

@Aman that worked! 환상적인 친구 감사합니다 :) – StuyvesantBlue

+0

위대한 : 디 .. 행운 – Aman

답변

1

JQuery와 아약스 콜백 기능 거기에

더 : http://api.jquery.com/jquery.post/

var jqxhr = $.post("example.php", function() { 
alert("success"); 
}) 
    .done(function() { 
    alert("second success"); 
    }) 
    .fail(function() { 
    alert("error"); // if something goes wrong 
    }) 
    .always(function() { 
    alert("finished"); // will always be executed, regardless of success or failure 
}); 
1

코멘트에 아만의 코드가 근무하고 그의 후속 대답은 간단 솔루션과 형식적인 해결책처럼 보인다 - 그러나 다른 사람에 대한 즉, 여기, 내 아마추어 코드를 사용하려고 아만의 의견에 따라 최종 결과 인 것 : 나는 posting.f 여기에 사용

jQuery(document).ready(function() { 

// Attach a submit handler to the form 
$('form[name="cart_quantity"]').submit(function(event) { 

// Stop form from submitting normally and initiate function 
event.preventDefault(); 
return addtocart(jQuery(this)); 

}); // eof Attach a submit handler to the form 

// function 
function addtocart(thisForm) { 

// Get some values from elements on the page: 
$("#contentss").fadeIn("slow"); 
action = thisForm.attr("action"); 

// Send the data using post 
var posting = $.post(action, thisForm.serialize()); 

// Process post-results request Success 
posting.done(function(data) { 

// find and put results in a div 
var shoppingCartSidebox = $(data).find('div#shoppingcart').html(); 
var numbernotify = $(data).find('div.numbernotify').html(); 
$('div#shoppingcartdiv').html(shoppingCartSidebox); 
$('div.numbernotify').html(numbernotify) 

// initiate slideDown/slideUp 
$(document.getElementById('contentss').style.display='none'); 
jQuery(document).ready(function() { 
$("#shoppingcartdiv").slideDown(); 
setTimeout(function() {$("#shoppingcartdiv").slideUp()}, 7000); 

}); // eof initiate slideDown/slideUp document ready 
}); // eof Process post-results 

// Process post-results request Fail 
posting.fail(function(data){ 
$(document.getElementById('contentss').style.display='none'); 
alert ("Failed"); 
}); // eof Process post-results request Fail 

// Process post-results request Success & Fail 
posting.always(function(data){ 
$("html, body").animate({ scrollTop: 0 }, "slow"); 
}); // eof Process post-results request Success & Fail 

} // eof function 
}); // eof main document ready 

기능 ail 및 posting.always는 당연히 (지금) 테스트를위한 자리 표시 자입니다. 그리고 뭔가 잘못되었다는 경고를 사용자에게 좀 더 사용자 친화적 인 것으로 끝낼 것입니다. 또한 내 자신의 초기 질문에 대답하기 위해 WAMP 서버의 플러그를 뽑아 카트에 제품을 추가하려고 할 때 작동했습니다. 따라서 인터넷 연결이 끊어 지더라도 작동 할 것이라고 가정합니다.

1

저는 jQuery의 약속 구현이 마음에 들지 않습니다 (그리고 저는 not the only one입니다). 이 경우, 내 이유는 이것이다 : 일반적으로

var jqxhr = $.post("example.php") 
.done(function(data) { 
    // You can get your data, but... 
}) 
.fail(function() { 
    // What is the error? Do I get a code? jQuery docs don't say... 
    alert("error"); 
}) 

, 내가 jQuery를에 AJAX 요청에 대한 긴 손 구문을 사용하는 것을 선호합니다. $.post 메서드는 shorthand method이며 개발자가 쉽게 작업 할 수 있습니다. 하지만 특정 구성 옵션을 숨겨서이 작업을 수행합니다. 오랜 경험을 통해 앱을 실제 서버에 배포하기 전에 거의 항상 필요하다는 것을 알게되었습니다.

따라서 매우 유용한 오류 처리기 errorstatusCode을 노출하는 $.ajax 메서드를 사용하는 것이 좋습니다. 다음과 같은 코드를 다시 작성할 수 있습니다 :

$.ajax({ 
    type: 'POST', 
    url: this.Form.attr("action"), 
    data: this.Form.serialize(), 
    success: function(data) { 
     // The rest of your success function 
     // i.e. from posting.done 
    }, 
    error: function(xhrReq, textStatus, errorThrown) { 
     // The rest of your error handling code 
     // i.e. from posting.fail 
     // You can also retry the request or report the specific error 
    }, 
    statusCode: // notice: statusCode singular 
    { 
     // Plain object syntax with integer status codes as the keys 
     403: function() { 
      alert("403 Forbidden. You do not have permission for this action."); 
     }, 
     500: function() { 
      alert("500 Internal Server Error. Try again later."); 
     } 
    } 
}); 

이 문서는 error 핸들러에 대해 이런 말 :

오류
유형 : 기능 (jqXHR jqXHR, 문자열 textStatus, 문자열 errorThrown)
요청이 실패 할 경우 호출 할 함수입니다.이 함수는 세 개의 인수를받습니다. jqXHR (jQuery 1.4.x, XMLHttpRequest) 객체, 발생한 오류 유형을 설명하는 문자열 및 선택적 예외 객체 (발생한 경우). 두 번째 인수 (null 이외)에 가능한 값은 "timeout", "error", "abort"및 "parsererror"입니다. HTTP 오류가 발생하면 errorThrown은 HTTP 상태의 텍스트 부분 (예 : "찾을 수 없음"또는 "내부 서버 오류")을받습니다. jQuery 1.5부터 오류 설정은 일련의 함수를 수용 할 수 있습니다. 각 함수가 순서대로 호출됩니다. 참고 :이 처리기는 도메인 간 스크립트 및 도메인 간 JSONP 요청에 대해 호출되지 않습니다. 이것은 Ajax 이벤트입니다. statusCode 핸들러에 대한

그리고이 :

에 statusCode (기본값 : {})
유형 : PlainObject
숫자 HTTP 코드와 기능의 객체가 응답이있을 때 호출되는 해당 코드. 예를 들어 다음은 응답 상태가 404 일 때 경고합니다. (위 참조)

요청이 성공하면 상태 코드 함수는 success 콜백과 동일한 매개 변수를 사용합니다. 오류 (3xx 리디렉션 포함)가 발생하면 오류 콜백과 동일한 매개 변수를 사용합니다.

그렇다면 해결 방법이 있다면 꼭 놓치지 마세요. 그러나 프로그래밍 요구 사항이 너무 복잡해지면 교육 바퀴가 떨어져 나간다는 점을 명심하십시오.

+1

고마워요. 내 초기 질문은 누군가가 현재 코드를 $ .ajax 솔루션으로 변환하는 데 도움이 될 것이라고 생각했지만, 겉보기에는 시도하지 않았기 때문에 샘플 시도를 요청하는 것이 두려웠습니다. 사실 나는 $ .ajax 솔루션의 레이아웃을 보았고 현재 코드를 사용하여 URL 및 데이터 필드를 어떻게 처리해야할지 몰랐다./그래서 나는 단지 내가 권했던 것을 고수했다. 당신은 실버 플래터로 나에게 그것을 건네 주었고, 지금 당신이 제공 한 코드를 사용할 것입니다 : D 다시 한번, 감사합니다! – StuyvesantBlue