简体   繁体   中英

JS array is not send to python script with AJAX

An idea is to send JS array which contains of HTML element ids to python script using AJAX . I have gone through multiple examples, on Stackoverflow as well but none of them worked so far.

My JS function is:

function callpc1() {
    var pcimages = document.querySelectorAll('.pcpics');
    test = [];
    test[0] = pcimages[0].id;
    test[1] = pcimages[1].id;
    test[2] = pcimages[2].id;
    $.ajax({
        type: "POST",
        url: "/~.../pcmove1.py",
        data: {
            test:test
        },
    });
}

Problem is python script gets no array data and variable remains empty on python side On python side I use getvalue method. I assume an error is with data: definition. And I would to avoid using JSON Please give a hint of what is wrongly defined here?

Edit


Code on python side

import cgi
page = cgi.FieldStorage()
listed =  page.getvalue('test', "unsuccess")
results = open("test.txt", "aw")
results.write (listed)
results.close()

Python's cgi module does processing that isn't appropriate for submitted JSON data. Specifically, content of a POST request is provided to a CGI module on stdin and cgi.FieldStorage() reads that and tries to convert it into something useful but assumes a normal form submission. Other data is provided as environment variables.

Adjusting your example, you may be able to get your post data as a Python object like this:

import sys, os
import json

length = os.environ["CONTENT_LENGTH"]
raw = sys.stdin.read(length)
data = json.loads(raw)
# Now we have a Python object representing the JSON data

# Convert the Python object back into a JSON formatted string
# and save to file
results = open("test.txt", "aw")
results.write(json.dumps(data))
results.close()

In the AJAX Post method, you should send test as a JSON, try this before making the Post method:

obj = JSON.stringify(test);

And then change your data parameter with:

"data": obj

It should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM