【问题标题】:Android app and Django server communciation: using jsonAndroid 应用程序和 Django 服务器通信:使用 json
【发布时间】:2015-02-13 02:01:56
【问题描述】:

我正在开发一个应用程序,该应用程序涉及 android 应用程序和 django 服务器之间的数据交换。我可以通过 http post 以 json 格式发送数据。但我无法在我的 django 代码(views.py)中解码 json。我是第一次开发应用程序。请帮忙。

【问题讨论】:

    标签: android json django


    【解决方案1】:

    如果您将 JSON 数据作为 serializeArray 提交,则它应该是您的 request.POST 中的 Python dict 在您的 views.py 中。所以你可以使用类似的东西:

        def this_view(request):
             if request.method == POST:
                   data_you_want = request.POST['key']
                   return HttpResponse(json.dumps(some_data_back_to_the_page), content_type='application/json')
             else:
                   return render(request,'some.html')
    

    【讨论】:

    • 请在下方查看我的回复
    【解决方案2】:

    Steven,我修改了如下代码: 从 django.http 导入 HttpResponse 从 django.views.decorators.csrf 导入 csrf_exempt

    @csrf_exempt
    def hello(request):
        if request.method == 'GET':
            return HttpResponse("get")
        elif request.method == 'POST':
            data = request.POST['GrpName']
            return HttpResponse("success")
    

    当我在 android 模拟器上运行我的应用程序时,在 toast 消息中我收到的是 html 源代码而不是“成功”

    【讨论】:

    • 您好,您可能需要发布一些 html 代码...我不太确定您如何将 json 数据发送到那里。
    • 感谢您的帮助
    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多