2017-02-22 5 views
3

는 좀 아약스 처음 ... 코드를하고 있어요 :오류가 발생해도 콘솔 오류가 나타 납니까?

jQuery를

form_ajax_promise = $.ajax({ 
    type : "POST", 
    url : '/orders/create_or_update', 
    dataType: 'json', 
    contentType: 'application/json', 
    data : JSON.stringify(params) 
}) 
form_ajax_promise.then(
    function(response) { 
    formSuccess(response) 
    }, 
    function(response) { 
    formFailure(response) 
    } 
) 

에게 컨트롤러

def create_or_update 
    if @object.save 
    # corresponds with formSuccess 
    render json: {"id" => @order.id}, status: 200 
    else 
    # corresponds with formFailure 
    render json: {"errors"=> @order.errors.full_messages}, status: 400 
    end 
end 

success 경로가 잘 작동합니다. ... formFailure 그냥 간단한 함수라고 가정하고 failure 경로를 테스트에서

function formFailure(response){ 
    console.log("successfully inside of formFailure") 
} 

내가 무슨 일이 일어나고 알았어 야하는 것은 console 위와 같이 해당 로그 메시지를 보여주고, 또한 나에게 오류를 보여주고 있다는 것입니다 :

Failed to load resource: the server responded with a status of 400 (Bad Request) 

이 오류가 발생합니까? 나는 $.then에 적절한 fail을 제공 한 이후에 그렇게 느껴지지 않았습니까?

편집 혼란에 대한

죄송합니다, 이것은 다수의 경우가 아니라 렌더링/재 직접, I I는 행동을하지 설명하기 위해 시도 된 이후 그냥 게으른되는 다른 코드를 절단했다 . 내 실수. 코드는 위에서 편집됩니다.

+0

'상태 : 400'으로 렌더링하고 있습니다. 따라서 올바른 행동입니다. – Sajan

+0

두 가지 질문 (1) 어떤 버전의 jQuery? (2)'form_ajax_promise'가 더 처리 되었습니까? –

+0

1) jQuery 2.2.4, 2) 더 이상 처리되지 않습니다 – james

답변

1

어쩌면 이렇게 될 것입니다. 이 @order

def create_or_update 
    # Your code here to create or update @order 
    if @order.save 
    # corresponds with formSuccess 
    render json: {"id" => @order.id}, status: 200 
    else 
    # corresponds with formFailure 
    render json: {"errors"=> @order.errors.full_messages}, status: 400 
    end 
end 
+0

죄송합니다. 그냥 코드를 축약하고 게으른 중인데, 그게 무슨 일 이니? – james

0

일반적으로 무효 인 경우에, 당신에게 @order이 성공적으로 저장 successerror를 반환 여러 렌더링 또는 리디렉션 오류 코드 결과 이런 종류의 것입니다. if 또는 return 문을 사용하는 것과 같은 조건부/분기 구문을 사용하지 않고 동일한 함수에서 다중 렌더링 또는 리디렉션을 사용하지 마십시오. 귀하의 경우에는

,

render json: {"errors"=> @order.errors.full_messages}, status: 400

은 콘솔에서이 오류가 표시되도록 (잘못된 요청입니다) 오류 코드 (400)를 수신 브라우저를 지시하는 표현되어있다. @Deepak Mahakale이 위에 공유 한 코드를 사용하는 것이 더 좋습니다.

희망이 있습니다.

+0

죄송합니다. 의견보기/수정 – james