weixin_33701564 2015-11-07 14:44 采纳率: 0%
浏览 93

将Webpy与AJAX结合使用

I am relatively new to web development and am trying to get the client javascript to send GET requests to a python script running on the server and the server to return data based on that request. I have tried adapting the examples of the webpy library I found online to no avail. Whenever a GET request is sent, the responseText attribute of XMLHttpRequest() returns the text of the python file rather than the data. Any advise would be much appreciated!

The javascript function:

function sendSerialCommand(selection, command) {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            if (command !== 5) {
                document.getElementById("output2").innerHTML = xmlhttp.responseText;
                document.getElementById("output2").style.color = "green";
            } else {
                document.getElementById("output1").innerHTML = xmlhttp.responseText;
                console.log(xmlhttp.responseText);
                document.getElementById("output1").style.color = "green";
            }
        }
    };

    xmlhttp.open("GET", pythonFileName + "?sel=" + selection + "?cmd=" + command, true);
    xmlhttp.send();
}

...and the test python script:

import web

urls = (
    '/', 'Index'
)
app = web.application(urls,globals())

#MAIN LOOP

class Index:
    def GET(self):
        webInput = web.input()
        return 'message: GET OK!'

if __name__ == "__main__":
        app.run()
  • 写回答

1条回答 默认 最新

  • weixin_33726313 2015-11-08 23:13
    关注

    The trick was to use the CGI library for python as such:

    #!/usr/bin/python
    
    # Import modules for CGI handling 
    import cgi, cgitb 
    
    # Create instance of FieldStorage 
    form = cgi.FieldStorage() 
    
    # Get data from fields
    first_name = form.getvalue('cmd')
    last_name  = form.getvalue('sel')
    
    print "Content-type:text/html
    
    "
    print "Hello %s %s" % (first_name, last_name)
    

    This captures the keys and data from the GET request and the print command returns data to the xmlhttp.responseText attribute on the client-side.

    The script has to be placed into a file the websever is able to execute the script from. That is usually the default /cgi-bin folder located in either /var/www or /etc.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。