简体   繁体   中英

ajax pass parameters to python script

I have this python CGI script that I got up and running using following command:

python3 -m http.server --cgi 8000

important part of the python script is this:

parameter = cgi.FieldStorage()
artiest = parameter.getvalue("artiest")
rijen_aantal = parameter.getvalue("rijen")
kolommen_aantal = parameter.getvalue("kolommen")

Now what I would like to do is in my html/javascript I would like to pass the values I am getting from a form to my cgi script.

In html i have written the following form using bootstrap:

<form class="form-inline" role="form" method="POST" action="cgi-bin/schuifpuzzel.py">
<div class="form-group">
    <label for="artiest">Artiest:</label>
    <input type="text" class="form-control margin-right" id="artiest">
</div>
<div class="form-group">
    <label for="rij">Rijen:</label>
    <input type="number" class="form-control margin-right" id="rij">
</div>
<div class="form-group">
    <label for="kolom">Kolommen:</label>
    <input type="number" class="form-control margin-right" id="kolom">
</div>
<button type="submit" class="btn btn-default">Submit</button>

And in javascript I have written following code that I am calling in the html header.

$(function () {

var artiest = document.getElementById("myForm").elements[0].value;
var rijen = document.getElementById("myForm").elements[1].value;
var kolommen = document.getElementById("myForm").elements[2].value;
$.ajax({
    url: 'cgi-bin/schuifpuzzel.py',
    type: 'post',
    datatype: "json",
    data: JSON.stringify({'artiest': artiest, "rijen": rijen, "kolommen": kolommen}),
    success: function(response) {
        alert(response);
    }
})

});

but this is for some reason not working. All it does is download the .py.

What am I doing wrong here?

UPDATE:

new problem. I think the posting problem is kind of solved.

But then I was getting following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource

I have solved that by using the solution posted by yoshyosh on this post

But now I am getting this error for some reason: 在此输入图像描述

I am not sure why because the path to my script is correct?

在此输入图像描述

Use .serialize() on your form to send the data as formdata, not as JSON.

$.ajax({
    ...
    data: $('.form-inline').serialize(),
    ...
})

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