gpt4 book ai didi

jquery - 使用 Bottle 使用 Rest Web 服务(JQuery 和 JSON)

转载 作者:行者123 更新时间:2023-12-01 05:51:43 26 4
gpt4 key购买 nike

我想使用这个返回 JSON 响应的其余 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>

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

最佳答案

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

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

关于jquery - 使用 Bottle 使用 Rest Web 服务(JQuery 和 JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21484279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com