sourcecode

플라스크에 있는 에이잭스에서 올라온 데이터를 어떻게 사용할 수 있나요?

codebag 2023. 3. 9. 22:02
반응형

플라스크에 있는 에이잭스에서 올라온 데이터를 어떻게 사용할 수 있나요?

jquery ajax에서 데이터를 POST하는 데 문제가 있습니다.

$('#clickme').click( function() {
    var data = save_input(); // data

    data['_sid'] = $survey_id;  // survey_id injected from flask
    data['_uip'] = $user_ip; // user_ip injected from flask, request.remote_addr

    $.ajax({
        type : "POST",
        url : "{{ url_for('mod.load_ajax') }}",
        data: JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8',
        success: function(result) {
            console.log(result);
        }
    });

    console.log(data);
});

코드로부터,data다음과 같은 javascript 객체입니다.

{
    'foo' : 'foo',
    'bar' : 'bar',
    'fo_' : 42,
}

내가 플라스크에서 하려는 것은:

@mod.route('/load_ajax', methods=["GET", "POST"])
def load_ajax():
    if request.method == "POST":
        # load _sid and _uip from posted JSON and save other data
        # but request.form is empty.
        # >>> request.form
        # ImmutableMultiDict([]) 
        return str(request.form)

Ajax 요청은 이루어지지만 데이터는 전송되지 않습니다.그렇습니다.console.log(data)의미 있는 데이터를 가지고 있다는 걸 알 수 있도록datajquery의 변수. 단, 요청.Ajax 보기의 양식이 비어 있습니다.데이터는 어디에 제출됩니까?

해라

 $.ajax({
    type : "POST",
    url : "{{ url_for('mod.load_ajax') }}",
    data: JSON.stringify(data, null, '\t'),
    contentType: 'application/json;charset=UTF-8',
    success: function(result) {
        console.log(result);
    }
});

그런 다음 서버에서 다음과 같은 데이터 변수를 참조할 수 있습니다.

request.json['foo']

콘텐츠 타입은 다음과 같이 지정되어 있습니다.application/json데이터는 안에 있습니다.request.json

예시와 같이 키 값 쌍을 보내는 것이 아니라 jQuery 데이터 옵션에 JSON 문자열을 할당합니다.코멘트에서 설명한 바와 같이 JSON을 문자열화해야 합니다.키(플라스크에서 JSON 문자열에 액세스하기 위해 사용됨)를 사용하여 객체를 작성한 후 jQuery 데이터 키에 할당합니다.

    $.ajax({
            type : "POST",
            url : "{{ url_for('mod.load_ajax') }}",
            data: {json_str: JSON.stringify(data)},
            contentType: 'application/json;charset=UTF-8',
            success: function(result) {
                console.log(result);
            }
        });

    @mod.route('/load_ajax', methods=["GET", "POST"])
    def load_ajax():
        if request.method == "POST":
            # load _sid and _uip from posted JSON and save other data
            # but request.form is empty.
            # >>> request.form
            # ImmutableMultiDict([]) 
            return str(request.form['json_str']
     )

플라스크 측면에서는 다음을 사용합니다.

data = request.get_json()

변수 데이터는 이제 당신이 ajax를 사용하여 보낸 사전을 가지고 있으며 이제 python으로 조작할 수 있습니다.

content Type을 삭제해 보셨습니까?플라스크에 데이터를 게시해야 합니다.

다음과 같은 가짜 데이터를 추가해 볼 수 있습니까?

hello 월드가 요청으로 도착했는지 확인하기 위해 데이터: {"hello":"world"}을(를) ajax에 입력합니다.형태

Ajax에서 데이터 가져오기(Flask)

HTML:

<input type="text" id="inputbox" autocomplete="off">

Js:

    $(document).ready(function(){
        $("#inputbox").on("input",function(e){
            inputbox = $("#inputbox").val();
            console.log(inputbox)
            $.ajax({
                method: "post",
                url: "/path",
                data: {inputbox},
                success:function(res){


                }
            })
        });
    });

.py:

search_value = request.form.get("text")

언급URL : https://stackoverflow.com/questions/14908864/how-can-i-use-data-posted-from-ajax-in-flask

반응형