【问题标题】:Django ajax HttpResponse json error Unexpected token dDjango ajax HttpResponse json 错误 Unexpected token d
【发布时间】:2014-02-11 03:45:47
【问题描述】:

我正在尝试使用medium-editor 做一个 Django ajax HttpResponse json。

view.py

def test(request, union_id):
if request.is_ajax():
    t = Union.objects.get(id=union_id)
    message = json.loads(request.body)
    t.description = message['description']['value']
    t.save()
    return HttpResponse(message, mimetype="application/json")
else:
    message = "Not Ajax"
    return HttpResponse(message)

Jquery(更新)

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $('#savecontentObj').click(function() {
        var contentObj = editor.serialize();
        obj = JSON.stringify(contentObj);
        $.ajax({
          url:"update",
            type: "POST",
            data: obj,
            dataType: "json",
            contentType: "application/json",
            success:function(response){
                console.log('success');
            },
            complete:function(){
                console.log('complete');
            },
            error:function (xhr, textStatus, thrownError){
                console.log(thrownError);
                console.log(obj);
            }
        });
    });

控制台日志

SyntaxError {stack: (...), message: "Unexpected token d"}
{"description":{"value":"<p>dddddd</p>"}}
complete 

它正在将“描述”保存到数据库,但我在 httpresponse 中没有取得成功,正如您在 console.log 中看到的那样。

非常感谢!

更新

url.py

url(r'^(?P<union_id>\d+)/update$', views.test),

【问题讨论】:

  • 尝试对数据进行字符串化:data: JSON.stringify(obj).
  • 谢谢,我已经在这里做了:obj = JSON.stringify(contentObj);
  • 哦,是的,对不起,我错过了。

标签: jquery python ajax django json


【解决方案1】:
def test(request, union_id):
if request.is_ajax():
    t = Union.objects.get(id=union_id)
    t.description = request.POST.get('description',None)
    t.save()
    HttpResponse(json.dumps(dict(status='updated')), mimetype="application/json")
else:
    message = "Not Ajax"
    HttpResponse(json.dumps(dict(status="Not Ajax")), mimetype="application/json")

$('#savecontentObj').click(function() {
        var contentObj = editor.serialize();
        $.ajax({
          url:"update",
            type: "POST",
            data: contentObj,
            dataType: "json",
            success:function(data){
                console.log(data.success);
            },
            complete:function(){
                console.log('complete');
            },
            error:function (xhr, textStatus, thrownError){
                console.log(thrownError);
                console.log(obj);
            }
        });
    });

确保您的 ajax url 不是根据您的视图方法,并且 csrf 令牌必须存在于序列化值中。

【讨论】:

  • 有了这个视图,我得到了IntegrityError: (1048, "Column 'description' cannot be null")。我用我的 url.py 代码更新了
  • 您可以调试您的代码,只需将 import pdb;pdb.set_trace() 放在第 t = Union.objects.get(id=union_id) 行之后。你有调试控制台。您可以检查 request.POST 中是否存在描述。如果不检查您的序列化值。
  • 我通过return HttpResponse(json.dumps(dict(status='updated')), mimetype="application/json") 获得了成功。非常感谢@Yogesh,我会继续尝试这个
  • 是的,我做到了。它需要json.dumps 上的return。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-10-18
  • 2017-04-16
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 2022-01-22
  • 2021-06-05
  • 2013-12-09
相关资源
最近更新 更多