U
U
Urbansamurai2016-01-18 18:34:15
Python
Urbansamurai, 2016-01-18 18:34:15

How to pass JSON object from JavaScript to CGI python script?

I googled everything, sort of figured out what JSON is, but I didn’t find a solution.

Tried to use myjson = json.load(sys.stdin) method like this - didn't help.

The task is simple: to pass an array of data to the python AJAX.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
Urbansamurai, 2016-01-18
@Urbansamurai

Everything worked like this:

function mix()
        {
        
            $.ajax({
                url: "cgi-bin/test.py",
                type: "post",
                data: JSON.stringify({'letters':letters,'intervals':intervals}),
                dataType: "json",
                success : function(response)
                {
                    $("#div").html(response);
                }
            });
            
        };

import json, sys

result = "success"

myjson = json.load(sys.stdin)
print myjson
# Do something with 'myjson' object

print 'Content-Type: application/json\n\n'
print json.dumps(result)    # or "json.dump(result, sys.stdout)"

S
Stalker_RED, 2016-01-18
@Stalker_RED

If you have python as a CGI script then why are you reading from stdin?
Use FieldStorage https://docs.python.org/2/library/cgi.html

V
Valery Ryaboshapko, 2016-01-18
@valerium

The json module has two functions: load and load s . The first one takes a file-like object as its first argument (roughly speaking, any object that has a read() method), the second one takes a string. Wang, that's the problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question