Ajax发布到Python cgi脚本

2024-10-01 11:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Ajax将值传递到pythoncgi。 几年前,我曾让这些测试JS和Python脚本正常工作,但现在我无法让它们工作。在

当我将JSON发布到cgi时,它得到状态代码:200ok。但回应是:“SyntaxError:JSON.parseJSON第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:

^{pr2}$

Tags: textidjsoninputdatatypescriptajax