如何用ajax从一个Python WSGI应用程序读取JSON对象如何用、应用程序、对象、ajax

2023-09-10 17:04:55 作者:次品无法替代

因此​​,这里是我的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',功能(数据){
    //数据==结果
});
 
Python Ajax请求及返回 json

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

 
精彩推荐
图片推荐