jquery – AJAX发布到Python cgi

前端之家收集整理的这篇文章主要介绍了jquery – AJAX发布到Python cgi前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Possible Duplicate:
07000

我有Apache2安装和Python工作.

我遇到了问题.我有两页.

一个是Python页面,另一个是带有JQuery的Html页面
我可以将Src改为google jquery链接.

有人可以告诉我如何让我的ajax帖子正常工作.

  1. $(function()
  2. {
  3. alert('Im going to start processing');
  4.  
  5. $.ajax({
  6. url: "saveList.py",type: "post",data: {'param':{"hello":"world"}},dataType: "application/json",success : function(response)
  7. {
  8. alert(response);
  9. }
  10. });
  11. });

和Python代码

  1. import sys
  2. import json
  3.  
  4. def index(req):
  5. result = {'success':'true','message':'The Command Completed Successfully'};
  6.  
  7. data = sys.stdin.read();
  8.  
  9. myjson = json.loads(data);
  10.  
  11. return str(myjson);

解决方法

这是一个示例html文件和附带的python CGI脚本,可以帮助您:

使用这个HTML:

  1. <html>
  2. <head>
  3. <Meta http-equiv="content-type" content="text/html; charset=utf-8">
  4.  
  5. <title>test</title>
  6. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  7. <script>
  8.  
  9. $(function()
  10. {
  11. $('#clickme').click(function(){
  12. alert('Im going to start processing');
  13.  
  14. $.ajax({
  15. url: "/scripts/ajaxpost.py",datatype:"json",data: {'key':'value','key2':'value2'},success: function(response){
  16. alert(response.message);
  17. alert(response.keys);
  18. }
  19. });
  20. });
  21. });
  22.  
  23. </script>
  24. </head>
  25. <body>
  26. <button id="clickme"> click me </button>
  27. </body>
  28.  
  29. </html>

这个脚本:

  1. #!/usr/bin/env python
  2.  
  3. import sys
  4. import json
  5. import cgi
  6.  
  7. fs = cgi.FieldStorage()
  8.  
  9. sys.stdout.write("Content-Type: application/json")
  10.  
  11. sys.stdout.write("\n")
  12. sys.stdout.write("\n")
  13.  
  14.  
  15. result = {}
  16. result['success'] = True
  17. result['message'] = "The command Completed Successfully"
  18. result['keys'] = ",".join(fs.keys())
  19.  
  20. d = {}
  21. for k in fs.keys():
  22. d[k] = fs.getvalue(k)
  23.  
  24. result['data'] = d
  25.  
  26. sys.stdout.write(json.dumps(result,indent=1))
  27. sys.stdout.write("\n")
  28.  
  29. sys.stdout.close()

单击按钮后,您可以看到cgi脚本返回:

  1. {
  2. "keys": "key2,key","message": "The command Completed Successfully","data": {
  3. "key2": "value2","key": "value"
  4. },"success": true
  5. }

猜你在找的jQuery相关文章