Passing variables between Python and Javascript

后端 未结 2 1523
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 16:39

Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed.

Depending on which item is selected in the list,

2条回答
  •  你的背包
    2021-02-02 17:18

    Funny, I've got web pages with JavaScript that talk to Python CGI modules that use SQLAlchemy.

    What I do is send AJAX request but with JSON request in the body instead of XML. Python CGI modules use standard json module to deserialize JSON into a dictionary.

    JavaScript side looks like this:

    function on_request_success(response) {
        console.debug('response', response);
    } 
    
    function on_request_error(r, text_status, error_thrown) {
        console.debug('error', text_status + ", " + error_thrown + ":\n" + r.responseText);
    }
    
    var request = { ... };
    jQuery.ajax({
        url: 'http://host/whatever.cgi',
        type: 'POST',
        cache: false,
        data: JSON.stringify(request),
        contentType: 'application/json',
        processData: false,
        success: on_request_success,
        error: on_request_error
    });
    

    And Python like this:

    request = json.load(sys.stdin)
    response = handle_request(request)
    print("Content-Type: application/json", end="\n\n")
    json.dump(response, sys.stdout, indent=2)
    

    Note, it doesn't use Python cgi module, since the whole request is passed as JSON in the body.

提交回复
热议问题