AJAX可以访问Django HttpResponse变量

时间:2022-03-07 02:28:40

I am writing a small test app for a bigger project. I would like to use asynchronously FileReader() to read a txt file from client side and pass the textbody to the Django server by using AJAX. When the server succeeds to get the "posted" text, it will return the length of the text. It worked well on the server and I got what I expected. But now I would like to pass the size of the text(length) back to the client and display it somewhere on the web page asynchronously. But failed... Here is my code:

我正在为一个更大的项目编写一个小测试应用程序。我想使用异步FileReader()从客户端读取txt文件,并使用AJAX将textbody传递给Django服务器。当服务器成功获取“发布”文本时,它将返回文本的长度。它在服务器上运行得很好,我得到了我想要的结果。但是现在我想将文本的大小(长度)传递回客户机,并在web页面的某个位置异步显示它。但是失败了……这是我的代码:

HTML

HTML

<script type="text/javascript">
    var render_text = function(csvFile, onLoadCallback){
        var reader = new FileReader();
        reader.onload = onLoadCallback;
        reader.readAsText(csvFile);
    }

    $(document).ready(function(){

        $("#id_csvFileInput").on("change", function(e){
            render_text(this.files[0], function(e){
                var text = e.target.result;
                $.ajax({
                    url: "",
                    type: 'POST',
                    async: true,
                    data: {'text': text},
                    success: function(data){
                        $("#id_test").text(data.size);
                    }
                });
            });
        });
    });

</script>

<p>
    <input type="file" name="csvFileInput" id="id_csvFileInput" accept=".csv">
</p>

<div>
    <p>Waiting for reponse context....</p>
    <span id="id_test">?</span>
</div>

View.py

View.py

# Home page.
@csrf_exempt
def home(request):
    template = 'hbvapp/home.html'
    context = {}
    if request.method == "POST" and request.is_ajax():
        context['test'] = request.POST.get('text')
        context['size'] = len(context['test'])
        print context['size']
        return render(request, template, context)
    else:
        return render(request, template)

ANY HELP WILL BE DEEPLY APPRECIATED ! Reagards

如有任何帮助,我们将不胜感激!Reagards

2 个解决方案

#1


2  

try it

试一试

from django.http import JsonResponse

    if request.method == "POST" and request.is_ajax():
        context['test'] = request.POST.get('text')
        context['size'] = len(context['test'])
        print context['size']
        return JsonResponse(context)
        #       ^^^^^

more details jsonresponse

更多细节jsonresponse

#2


1  

you can send it this way also:

你也可以这样发送:

context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return HttpResponse(json.dumps(context), content_type='application/json')

and in you js you can access it like this:

在you js中你可以这样访问它:

success: function(data){
                    $("#id_test").text(data['size']);
                }

#1


2  

try it

试一试

from django.http import JsonResponse

    if request.method == "POST" and request.is_ajax():
        context['test'] = request.POST.get('text')
        context['size'] = len(context['test'])
        print context['size']
        return JsonResponse(context)
        #       ^^^^^

more details jsonresponse

更多细节jsonresponse

#2


1  

you can send it this way also:

你也可以这样发送:

context['test'] = request.POST.get('text')
context['size'] = len(context['test'])
print context['size']
return HttpResponse(json.dumps(context), content_type='application/json')

and in you js you can access it like this:

在you js中你可以这样访问它:

success: function(data){
                    $("#id_test").text(data['size']);
                }