【问题标题】:Consuming Rest Web Service with Bottle (JQuery and JSON)使用 Bottle(JQuery 和 JSON)使用 Rest Web 服务
【发布时间】:2014-02-24 09:30:31
【问题描述】:

我想使用这个返回 JSON 响应的 REST Web 服务:

web_service.py

from bottle import route, run

@route('/example')
def example():
    return {"result_1" : 3, "result_2" : 5}

run(host='localhost', port=8080)

我的 JavaScript 文件是这样的:

java_s.js

$(document).ready(function() {
    $.ajax({
        type: "GET"
        url: "http://localhost:8080/example",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(resp){
            $('.result_1').append(resp.result_1)
            $('.result_2').append(resp.result_2)
        }
    })
});

而我想要使用 Web 服务的 html 文件是:

index.html

<head>
    <title>example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="java_s.js"></script>
</head>

<body>
    <div>
        <p class="result_1">result 1: </p>
        <p class="result_2">result 2: </p>
    </div>
</body>

但是,当我打开索引文件时,没有显示结果。你能给我一些建议来解决这个问题吗?谢谢!

【问题讨论】:

  • 'localhost:8080/example' 返回什么?
  • 它返回: {"result_1" : 3, "result_2" : 5} 我想在 html 文件中显示该结果。我在网络服务中添加了语句:response.content_type = "application/json" 但它不起作用。

标签: jquery json web-services rest bottle


【解决方案1】:

您返回的是 python dict 对象,而不是 json 字符串。您可以手动对字符串进行编码,也可以使用例如 json 库来实际输出 json。

import json 添加到文件的开头,然后更改为return json.dumps({"result_1" : 3, "result_2" : 5}) 以返回从您的python dict 对象创建的实际json 字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多