如何用ajax从一个Python WSGI应用程序读取JSON对象 [英] how to Read JSON object using ajax from a python wsgi application

查看:796
本文介绍了如何用ajax从一个Python WSGI应用程序读取JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,这里是我的Python应用程序。

 从wsgiref.simple_server进口make_server
进口JSON

高清应用(ENVIRON,start_response):
   结果= [{名:约翰·约翰逊,街:奥斯陆西555,时代:33}]
   response_body = json.dumps(结果)
   状态=200 OK
   response_headers = [('内容类型,text / plain的),
                  (内容长度,STR(LEN(response_body)))]
   start_response(状态,response_headers)
   返回[response_body]

的httpd = make_server('localhost'的,8051,应用程序)
httpd.handle_request()
 

所以,现在我要的是得到的返回值,显示在网页上。 我读了有功能jQuery.getJSON。但我不太明白它是如何工作的。 http://api.jquery.com/jQuery.getJSON/

感谢。

解决方案

  $ .getJSON('的http://本地主机:8051').success(功能(数据){
    //这里`data`将是你`result`在你的Python应用程序
});
 

如果您的jQuery版本< 1.5

  $ .getJSON('的http://本地主机:8051',功能(数据){
    //数据==结果
});
 

PS:如果你返回一个JSON对象,你最好设置内容类型应用程序/ JSON

So here is my python application.

from wsgiref.simple_server import make_server
import json

def application(environ, start_response):
   result = [{"name":"John Johnson","street":"Oslo West 555","age":33}]
   response_body = json.dumps(result)
   status = '200 OK'
   response_headers = [('Content-Type', 'text/plain'),
                  ('Content-Length', str(len(response_body)))]
   start_response(status, response_headers)
   return [response_body]

httpd = make_server('localhost',8051,application)
httpd.handle_request()

So Now all I want is to get the return value to display on the web. I read there is function jQuery.getJSON. but I don't quite understand how it works. http://api.jquery.com/jQuery.getJSON/

Thanks.

解决方案

$.getJSON('http://localhost:8051').success(function(data) {
    //here `data` will be your `result` in your python application
});

If your jQuery version < 1.5

$.getJSON('http://localhost:8051', function(data){
    // data == result
});

PS: if you return a json object, you'd better set the Content-Type to application/json

这篇关于如何用ajax从一个Python WSGI应用程序读取JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆