如果我有一个这样的链接<a href="/account/user">Get User Data</a>
指向我自己的服务器内的视图,有没有办法发送一个json对象(也许只是带有ajax?)到另一个外部服务器并检索答案?像这样:
from django.shortcuts import render
def profile(request):
#send a json object to another server like http://www.myotherserver.com/user
#get the answer and process it
return render(request, 'accounts/profile.html' ,
{'profile_user': data_from_the_external_server})
以上我可以用jquery-ajax实现它,但我只是想知道我是否可以这样做...
提前致谢。
答案 0 :(得分:1)
当然可以。为什么不可能?
如果没有必要,请不要在AJAX中编写代码。
你需要做两件事,你需要准备JSon发送,然后你需要将它发送到你想要的API:
也不要在你的视野中直截了当。为它创建一个新类。所以在你看来你会有类似的东西:
def profile(request):
# instantiate your service here (better with DI)
profile_user = my_service.get_profile_user()
return render(
request,
'accounts/profile.html' ,
{
'profile_user': profile_user
}
)
答案 1 :(得分:0)