【问题标题】:jquery; django; parsing httpresponsejQuery; django;解析http响应
【发布时间】:2010-05-27 20:09:58
【问题描述】:

我在解析 http 响应时遇到问题。我尝试向客户端发送一些值

>>>>return HttpResponse(first=True,second=True)

解析时:

$.post('get_values',"",function(data){
                alert(data['first']); //The alert isn't shown!!!
            });

从 httpresponse 中提取值的正确方法是什么

也许我在创建回复时犯了一个错误..

【问题讨论】:

    标签: jquery django httpresponse


    【解决方案1】:

    如果您尝试使用 json,您可以这样做:

    Django

    data = json.dumps({"FIRST":True, "SECOND":False})
        return HttpResponse(data, mimetype="application/json")
    

    得到它:

    jQuery

    $.getJSON(url, [data], function(data){
                    alert(data['first']);
                });
    

    getJSON 是一个 jquery 简写函数,相当于 $.ajax 函数:

    $.ajax({
      url: url,
      dataType: 'json',
      data: data,
      success: callback
    });
    

    【讨论】:

    • 非常感谢!你拯救了我的一天
    【解决方案2】:

    如果您将 HttpResponse 设为 json:

    return HttpResponse("{\"first\":true,
    \"second\":false}")
    

    那么您可以将其作为 json 接收

    $.post('get_values',"",function(data){
                    alert(data['first']); //The alert isn't shown!!!
                },"json");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 2018-06-29
      • 2014-05-27
      相关资源
      最近更新 更多