2017-09-06 14 views
0

Ok! 플라스크 웹 앱을 만들고 있는데, 아약스를 사용하여 json 데이터를 보내고 싶습니다. 여기 내 코드가 있습니다 !! html 및 js의 경우 :ajax 요청으로 잘못된 json으로 인해 플라스크에 400 오류가 발생합니다.

<!DOCTYPE html> 
<html > 
<head> 
    <meta charset="UTF-8"> 
    <title>Check your Grades</title> 
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
     <script src="{{ url_for('static', filename='js/bootstrap3-typeahead.min.js')}}"></script> 
     <script type="text/javascript" src="{{ url_for('static', filename='js/index.js')}}"></script> 
     <link rel="stylesheet" href="{{url_for('static', filename='css/style.css')}}"> 
</head> 

<body> 
    <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'> 
<form id="predict-form" method="POST"> 
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/> 
    <p> welcome to grade predictor app,</p> 
    <p>Dear Plateform,</p> 
    <p>je viens 
    <label for="SCHOOL_RIGHT"> de </label> 
    <input class="typeahead" type="text" name="SCHOOL_RIGHT" id="SCHOOL_RIGHT" minlength="3" placeholder="(votre ecole de provenance)" data-provide="typeahead" autocomplete="off" required> et </p> 

    <p>dans 
    <label for="OPTION_RIGHT">l'option</label> 
    <input class="typeahead" 
     name="OPTION_RIGHT" id="OPTION_RIGHT" data-provide="typeahead" placeholder="(choisissez votre option)" required> 
    </p> 
    <p>j'ai obtenu 
    <label for="DIPPERC"></label> 
    <input type="number" name="DIPPERC" min="50" max="100" id="DIPPERC" placeholder="(Poucentage du 
    diplome)" required> % à l\'exetat 
    </p> 

    <p> 
    <button type="submit"> 
     <svg version="1.1" class="send-icn" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100px" height="36px" viewBox="0 0 100 36" enable-background="new 0 0 100 36" xml:space="preserve"> 
     <path d="M100,0L100,0 M23.8,7.1L100,0L40.9,36l-4.7-7.5L22,34.8l-4-11L0,30.5L16.4,8.7l5.4,15L23,7L23.8,7.1z M16.8,20.4l-1.5-4.3 
    l-5.1,6.7L16.8,20.4z M34.4,25.4l-8.1-13.1L25,29.6L34.4,25.4z M35.2,13.2l8.1,13.1L70,9.9L35.2,13.2z" /> 
     </svg> 
     <small>send</small> 
    </button> 
    </p> 
</form> 
<script > 
var csrf_token = "{{ csrf_token() }}"; 
    // this will send a token each time before a session started 
    $.ajaxSetup({ 
     beforeSend: function(xhr, settings) { 
      if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) { 
       xhr.setRequestHeader("X-CSRFToken", csrf_token); 
      } 
     } 
    }); 
    //submit form data 
    $("form#predict-form").submit(function(e){ 
    console.log("form submitted") 
    e.preventDefault(); 
    var data = {} 
    var Form = this; 
    //Gathering the Data 
    //and removing undefined keys(buttons) 
    $.each(this.elements, function(i, v){ 
      var input = $(v); 
     data[input.attr("name")] = input.val(); 
     delete data["csrf_token"]; 
     delete data["undefined"]; 
    }); 
    data["DIPPERC"] = data["DIPPERC"]/100.0 
    //Form Validation goes here.... 
    //Save Form Data........ 
    $.ajax({ 
     cache: false, 
     url : "{{url_for('predict')}}", 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     data : JSON.stringify(data), 
     success : function(callback){ 
      //Where $(this) => context == FORM 
        console.log("data sucessfuly submitted") 
        console.log(JSON.parse(callback)); 
     }, 
     error : function(){ 
      console.log('erroor') 
     } 
    }); 

    }) 
</script> 
</body> 
</html> 

나는 모든 것을 시도했지만 여전히 400 오류가 발생했습니다. 관련 질문은 모두 확인했지만 아무 것도 확인하지 않았습니다.

하지만 내 연구는 400 오류가에 따라이 발생 될 수 있음을 보여줍니다 :이

는 HTTP 400 잘못된 요청 응답 상태 코드가 있음을 나타냅니다 : here에서

  • 라고 있어요 서버가 유효하지 않은 구문으로 인해 요청을 이해할 수 없습니다. 클라이언트는 수정하지 않고이 요청을 반복해서는 안됩니다.

  • CSRF 토큰 이미 토큰을 추가 한 this 누락하고 (이미 그것을하지 않는다 아무것도) 설정되지 csrf.exempt 아무것도하지만,
  • 의 ContentType과 applicationType과 경로에 데이터를 보내려고
  • 내가 올바른 JSON 데이터이 문제가 발생할 수 있습니다 무엇 그래서
  • 을 보내고있다 (에서) ??? :
  • 이미 공식 플라스크 문서에서 확인 그들은 말한다

    if request.method == 'POST': 
        print "hello----------------------" 
        print request.method 
        print request.get_json(force=True) 
    return "done " 
    
: 여기

데프) (예측 predictions.route ('/ 예측/예측 /'방식 = 'GET', 'POST']) @ 내 단순한 뷰 함수 난 내 경로에 파이썬을 통해 직접 데이터를 전송 내 테스트에서

참고가이 코드와 함께 작동 :

def test_1_can_connect_post(self): 
     """ 

     Test API can create a (POST request) 

     """ 
     new_student = {'DIPPERC':0.60, 'SCHOOL_RIGHT':'itfm/bukavu', 'OPTION_RIGHT':'elec indust'} 


     res = self.client().post('predictions/predict/', data=json.dumps(new_student), content_type='application/json') 

     self.assertEqual(res.status_code, 201) 

시를 : 나는 약간의 일을보고 싶어하지만 모르는 것을 확신합니다, 뭔가 잘못되었을 수도 있습니다. 아약스 ansynchrous ..... 당신은 문자열로 데이터를 변환 할 필요가 없습니다

답변

0

은 : 당신이 문자열을 게시 할 수 있도록 JSON.stringify

$.ajax({ 
    cache: false, 
    url : "{{url_for('predict')}}", 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    data : data, 
    success : function(callback){ 
     //Where $(this) => context == FORM 
       console.log("data sucessfuly submitted") 
       console.log(JSON.parse(callback)); 
    }, 
    error : function(){ 
     console.log('erroor') 
    } 
}); 

당신은 문자열로 데이터를 변환 다음 JSON.stringify 제거 JSON 없음.

+0

빠른 응답을 주셔서 감사합니다.하지만 아무 것도 변경하지 않으려 고 시도하십시오! 보내는 데이터는 json으로 인코딩해야하는 dict입니다. –

0

좋아, 디버깅 7 일 난 그냥 내 문제에 대한 해결책을 발견 한 후 : 나는 JQuery와 사용을 중지하고 I됩니다 지금부터 내 미래의 웹 개발 에 대한

  1. : 을 나는 두 가지를 '곧 내가 그렇게 내 코드를 내가 자바 스크립트 일반을 사용하기로 결정, 그 좋은 이유를 찾을 것이라고 확신 해요 여기에 내가 요청을 보낼 때 사용하는 코드입니다 :

    var csrf_token = "{{ csrf_token() }}"; 
    // this will send a token each time before a session started 
    var form = document.getElementById("predict-form"); 
    
    form.onsubmit = function (e) { 
    // stop the regular form submission 
    e.preventDefault(); 
    
    // collect the form data while iterating over the inputs 
    var formEntries = new FormData(form).entries(); 
    var data = Object.assign(...Array.from(formEntries, ([x,y]) => ({[x]:y}))); 
    delete data["csrf_token"]; 
    data["DIPPERC"] = data["DIPPERC"]/100.0 
    
    console.log(data); 
    // construct an HTTP request 
    var xhr = new XMLHttpRequest(); 
    xhr.open(form.method, form.action, true); 
    xhr.setRequestHeader("X-CSRFToken", csrf_token); 
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); 
    // send the collected data as JSON 
    xhr.send(JSON.stringify(data)); 
    
    xhr.onloadend = function() { 
    console.log('blallala ') 
    }; 
    }; 
    

    이이 위해이었다가 자바 스크립트 부분 난 내가

is_json 플라스크 요청 객체의 속성이 2 개 라인을 플라스크에 공식 문서에서 here을 가서 발견

  • 내 서버에 좋은 JSON 개체를 보내는 것을 확신했다 : 이 요청이 JSON인지 여부를 나타냅니다. 기본적으로 요청은 mimetype이 application/json 또는 application/* + json 인 경우 JSON 데이터를 포함하는 것으로 간주됩니다.

  • 데이터 들어오는 요청 그것이 마임와 함께 제공된 경우 문자열로 데이터 플라스크가

    를 처리하고이 내 백엔드 코드를 변경하지 않습니다를 포함합니다 :

    @predictions.route('/predictions/predict/', methods=['GET', 'POST']) 
    def predict(): 
        """ 
    
        the main methode use to predict 
    
        """ 
        if request.method == 'POST': 
         print "hello----------------------" 
         print request.is_json 
         print request.data 
         print '-----------------------------------------' 
        return "done " 
    

    그리고 VOILA !!!! 200 상태 코드와 데이터를 파이썬 사전으로 가져옵니다.