Ajax发布到Python cgi脚本

时间:2016-12-11 15:42:45

标签: javascript python json ajax cgi

我正在尝试使用Ajax将值发布到Python cgi。 几年前,我在测试JS和Python脚本时工作,但现在我无法让它们工作。

当我将一个JSON发布到cgi时,它获得状态代码:200 OK。但响应:" SyntaxError:JSON.parse在JSON"第34行的第1行意外结束数据;

知道我做错了什么:

HTML文件:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <h1>Test Ajax POST</h1>
    <form id="postform">
      <input type="text" name="myquery" id="query" />
    </form>
    <input id="submit" type="submit" name="submit" value="Go!">
    <p id="response"></p>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">

$('input#submit').click(
    function(){
        var formVal= $("#query").val();
        console.log(JSON.stringify({'myquery': formVal}));

        //Ajax POST
        $.ajax({
            contentType:"application/json",
            type: "POST",
            data:JSON.stringify({'myquery': formVal}),
            dataType:"json",
            url: "http://localhost/cgi-bin/test_ajax.cgi", //the url ofthe cgiscrip\
            success: function(data){
                console.log('success');
                if(data){
                    console.log(data.success, data.msg);
                    $('p#response').text(data.msg)
                }

            }
        })

    }
)
</script>
  </body>
</html>

Python CGI:

#!/usr/bin/env python
import cgitb; cgitb.enable()
import cgi, os, json, sys

method = os.environ.get("REQUEST_METHOD")

result = {'success':'true', 'msg': " was posted by you"}
print "Content-type: application/json\n\n"
print json.dumps(result)

0 个答案:

没有答案