在浏览器中显示HTTP响应的内容而不刷新



我是Django的新手,我不知道我想要的东西是否可以通过这种方式实现
我有一个简单的c++客户端,它必须使用HTTP请求(post方法(向我的Django服务器发送一个包含Json数据的char*数组(我使用cpp-httplib在c++中发送HTTP请求(
数据发送成功问题是我也想在浏览器中查看Json数据,但我未能做到。
客户端和服务器都在同一台机器上运行,服务器在本地主机上
这是我的**视图.py**
def PostFunc(request):
if request.method == 'POST':
print(request.POST)
print(request.body)
result = request.body
print(result)
return HttpResponse(result)

myurls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('',PostFunc),
]

这是我的客户端代码

int main(){
Client cli("127.0.0.1",8000);
char* testJson = {"[{"name":"Visual Studio Enterprise 2017","version":"15.0.26228.4"}]"};
auto res = cli.Post("/", testJson, "application/json");
cout << res->status;
system("pause");
return 0;
}

Django 3.0.8版本
Python 3.8.4rc1
感谢您抽出时间回答我的问题,并告诉我是否需要任何其他信息。

如果您想通过Json对象处理Django,请尝试以Json的形式发送对象,并以Json形式返回对象。

Usage
Typical usage could look like:
>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'

此外,当您将对象POST到Django时,出于测试目的,尝试从csrf令牌中免除视图。

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')

Djano rest框架致力于处理Json对象了解更多https://www.django-rest-framework.org/

好吧,我会发布对我有用的东西,以防有人遇到同样的问题
对于我的特定需求,我发现使用模板更方便
如注释中所述,在POST请求之后,Get请求将通过重定向到同一URL来为您获得结果
视图.py

@csrf_exempt
def post(request):
if request.method == 'POST':
recv = request.POST.get('key')
print(recv)
ListProgram.objects.create(name=recv)
return redirect(request.path)
else:
obj = ListProgram.objects.all()
return render(request,'list/response.html',{'message':obj})

response.html

<html>
<head>
<meta charset="UTF-8">
{% load static %}
<link type="text/css" rel="stylesheet"  href="{% static "list/styleResponse.css" %}"/>
<title>HTTP RESPONSE</title>
</head>
<body>
<h3>response changed</h3>
{% if message %}
<textarea rows="5" cols="35">
{% for s in message %}
key:{{s}}
{% endfor %}
</textarea>
{% else %}
<p>No data is available.</p>
{% endif %}
</body>
</html>

我是一个初学者,如果有任何关于如何改进的建议,我将不胜感激!

最新更新