发送JSON到Django模板


                    

我有一个非常基本的Django视图,一旦它收到请求,就应该向用户正在访问的页面发送响应,以便我可以在该页面上显示消息,而不必刷新页面。 / p>

这是我的观点:</ p>

  def操作(请求):
     响应=''
     如果request.method =='POST':
         如果request.POST.get('ajaxform',False)=='提交':
             数据= request.POST.get('formdata',False)
             mymodel = Userdata()
             mymodel.save()
             响应=“已提交!”

     返回HttpResponse(json.dumps(response),content_type ='application / json')
</ code> </ pre>

基本上,收到POST请求后,该视图应向模板发送JSON响应,并显示消息 Submitted </ code>。 </ p>

当我浏览模板时,在我的Dev工具上,此视图有效,我可以看到页面正在接收JSON响应 Submitted </ code>,但是我不知道如何显示它 使用Jquery。</ p>

有人可以指出我如何创建仅当Django视图接收到Json响应时才触发的Jquery函数吗?</ p>

基本上,在这种情况下,当Django视图触发响应 Submitted </ code>时,我的Jquery函数应该接收该消息并对其进行处理。</ p>

我尝试过:</ p>

  $。ajax({
   网址:“ / mytemplate / Action”,
   类型:“获取”,
   dataType:'json',
   成功:功能(数据){
     console.log(数据)
   }
});
</ code> </ pre>

此功能的问题是,尽管我可以在“网络”选项卡上看到响应,但是控制台上什么都没有打印。</ p>
     </ div>

展开原文

原文

I have a very basic Django view that, once it receives a request, should send a response to the page that the user is visiting, so that i can display a message on that page, without having to refresh the page.

Here is my view:

def Action(request):
    response = ''
    if request.method == 'POST':
        if request.POST.get('ajaxform', False) == 'submit':
            data = request.POST.get('formdata', False)
            mymodel = Userdata()
            mymodel.save()
            response = 'Submitted!'

    return HttpResponse(json.dumps(response), content_type='application/json')

Basically, when a POST request is received, this view should send a JSON response to the template with the message Submitted.

This view works, when i'm browsing my template, on my Dev tools i can see the JSON response Submitted being received by the page, but i don't understand how can i show it using Jquery.

Can someone point me out on how could i create a Jquery function that is triggered only when a Json response is received by a Django view?

Basically, in this case, when the Django view fires the response Submitted, my Jquery function should receive that message and do some stuff with it.

I tried this:

$.ajax({
  url: "/mytemplate/Action",
  type: 'get',
  dataType: 'json',
  success: function (data) {
    console.log(data)
  }
});

The problem with this function, though, is that nothing is being printed in my console, although i can see the response on my Network tab.

1个回答


我的猜测是,由于您在字符串中调用json.dumps,因此jQuery也收到了一个字符串。 也许尝试在您的视图中调用json.dumps({'response':'Submitted!')。</ p>

一个更简单的解决方案可能是使用“ .done”回调,该回调在发布请求成功后触发。 这样,您将不需要来自python视图的特定响应。 这样做,一个简单的HttpResponse('true')应该可以工作。</ p>

有关.done回调的更多详细信息,请参见: https://api.jquery.com/jquery .get / </ p>

澄清后编辑</ strong> </ p>

第一个问题在您看来。 在那里,您指定了</ p>

  if request.method =='POST':
</ code> </ pre>

但是您的ajax请求正在使用GET方法</ p>

 类型:“ get”,
</ code> </ pre>

除此之外,您仍然发送字符串响应,而不是“ stringfied”字典。</ p>

我做了一个与您的帖子类似的工作示例。 IMO,您的看法应该是:</ p>

  def操作(请求):
     响应=''
     如果request.method =='POST':
         如果request.POST.get('ajaxform',False)=='提交':
             数据= request.POST.get('formdata',False)
             mymodel = Userdata()
             mymodel.save()
             响应=“已提交!”

     返回JsonResponse({'resp':response})
</ code> </ pre>

为了发出请求并处理响应,我制作了一个$ .post,它更加简洁</ p>

  $。post(“ / mytemplate / Action”,
        参数,
        功能(数据)
        {
            console.log(数据)
        }
        )
</ code> </ pre>
     </ div>

展开原文

原文

My guess would be that, since you are calling the json.dumps in a string, your jQuery is also receiving a string. Maybe try calling json.dumps({'response': 'Submitted!') in your view.

An easier solution may be to use the ".done" callback, which is triggered after the post request is successful. This way, you won't need a specific response from the python view. Doing this, a simple HttpResponse('true') should work.

More specifics about the .done callback here: https://api.jquery.com/jquery.get/

Edit after clarification

The first problem is in your view. There, you specified

if request.method == 'POST':

but your ajax request is using the GET method

  type: 'get',

Besides that, you still sending a string response, and not an 'stringfied' dictionary.

I made an working example similar to your post. IMO, your view should be:

def Action(request):
    response = ''
    if request.method == 'POST':
        if request.POST.get('ajaxform', False) == 'submit':
            data = request.POST.get('formdata', False)
            mymodel = Userdata()
            mymodel.save()
            response = 'Submitted!'

    return JsonResponse({'resp': response})

For making the request and dealing with the response, I made a $.post, which is more concise

$.post("/mytemplate/Action", 
       params,
       function( data )
       {
           console.log(data )
       }
       )

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐