O. Barinov O. Barinov - 1 year ago 72
Ajax Question

JS array is not send to python script with AJAX

An idea is to send

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

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;
type: "POST",
url: "/~.../pcmove1.py",
data: {

Problem is python script gets no array data and variable remains empty on python side
On python side I use
method. I assume an error is with
definition. And I would to avoid using

Please give a hint of what is wrongly defined here?


Code on python side

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

Answer Source

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download