簡體   English   中英

無法解析通過python / flask中的jQuery通過AJAX發出的JSON POST請求

[英]Unable to parse JSON POST request made through AJAX with jQuery in python/flask

我正在嘗試使用python腳本中的jQuery解析通過AJAX發出的POST請求。 該請求的構造如下:

request.js

function get_form_data($form){
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
         indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
}

uri = location.protocol + '//' + location.host + "/sign_up";
method = "POST";
formId = "#signup_form_id";

$form = $(formId);
form_data = get_form_data($form);

// Set-up ajax call
var request = {
    url: uri,
    type: method,
    contentType: "application/json",
    accepts: "application/json",
    cache: false,
    dataType: "json",
    data: JSON.stringify(form_data)
};
// Make the request
$.ajax(request).done(function(data) { // Handle the response
    // Attributes are retrieved as object.attribute_name
    // alert(obj.count);
    console.log("Data from sign up from server: " + data);
    jsonObject = JSON.parse(data);
    if(jsonObject.successSignUp === false) {
        // Signup failed we show the welcome page
        alert("Sign-up failed!");
    } else {
        alert("Sign-up complete!");
    }
    // Show the welcome page regardless whether the sign up failed or not
    document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML;
}).fail(function(jqXHR, textStatus, errorThrown) { // Handle failure
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error on sign up: " + textStatus + ' : ' + errorThrown);
        }
);

觀看firebug中的請求調用,表明請求已正確發送(帶有適當的標頭和正文的JSON對象發送到了預期的URL):

標頭:

標頭

請求:

請求

在服務器端檢索JSON:

serverside.py

@app.route('/sign_up', methods=['POST'])
def sign_up_helper():
    # The received JSON object is parsed
    # data = request.get_json(force=True)  I've tried all variations. Same result
    # data = json.loads(data)
    data = request.json
    data = json.loads(data)

    with open('data.txt', 'w') as outfile: # Strangely a file is not even created in web root directory
        json.dump(data, outfile)

    # We explicitly retrieve the object's attribute values
    s_fname = data['s_fname']
    s_lname = data['s_lname']
    s_city = data['s_city']
    s_country = data['s_country']
    sex = data['sex']
    s_email = data['s_email']
    s_password = data['s_password']

    json_obj = sign_up(s_fname, s_lname, s_city, s_country, sex, s_email, s_password)

    resp = Response(response=json_obj,
                    status=200, \
                    mimetype="application/json")
    return(resp)


def sign_up(s_fname, s_lname, s_city, s_country, sex, s_email, s_password):
    """
    check if the email exists in the database. We (insecurely) rely on client side validation for the input fields.
    """
    data = query_db('SELECT * FROM Users WHERE email = ?', [s_email], one=True)
    if data is not None:
        return jsonify(
            successSignUp=False,
            message="Email already exists"), 400

    insert_db('INSERT INTO Users  (email, firstname, lastname, gender, city, country, password) \
        VALUES (?, ?, ?, ?, ?, ?, ?)',
              [s_email, s_fname, s_lname, sex, s_city,
               s_country, generate_password_hash(s_password)])
    return jsonify(
        successSignUp=True,
        message="Account created successfully")

以下例外:

TypeError: expected string or buffer

生成時,大概是在訪問JSON對象的元素時。 整個堆棧跟蹤如下:

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\mg13\Desktop\School\WebPython\twidder\twidder\app\server.py", line 126, in sign_up_helper
    data = json.loads(data)
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

我不明白為什么沒有一個與在服務器端創建/接收到的請求具有相同屬性和值的JSON對象。

訪問json鍵的正確方法是:

s_fname = data.get('s_fname','')

如果您在請求正文中沒有密鑰,它將處理異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM