【问题标题】:In django how to send json object using XMLHttpRequest in javascript在 django 中,如何在 javascript 中使用 XMLHttpRequest 发送 json 对象
【发布时间】:2020-09-26 07:09:12
【问题描述】:

请帮助我如何发送 json 对象并在 django 中接收它的 views.py。

我的脚本:

var obj={ 'search_name':search_name,'search_email':search_email };
jsonobj=JSON.stringify(obj);
//alert(jsonobj);
var xhr=new XMLHttpRequest();
xhr.open('POST',"viewprofile",true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(jsonobj);

【问题讨论】:

  • 欢迎来到 SO,你能检查一下这个问题吗,可能这是重复的。 stackoverflow.com/questions/24068576/…
  • 我试过了,var headers = {'content-type': 'application/json'} var r=xhr.post("viewprofile", data=json.dumps(jsonobj), headers=headers ),它在 this-> json.dumps(jsonobj) 中给出 json not defined 错误 .... 这应该是 JSON 吗?

标签: javascript python django xmlhttprequest


【解决方案1】:

在纯 JavaScript 中使用 XMLHttpRequest()。

XMLHttpRequest 是一种 API,它提供客户端功能以在客户端和服务器之间传输数据。

xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4 && xhr.status == 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.name)
    }
}
var data = JSON.stringify({"email":"tomb@raider.com","name":"LaraCroft"});
xhr.send(data);

使用 AJAX 调用(首选方式)

    $.ajax({
        url: "https://youknowit.com/api/",
        type: "POST",
        data: { apiKey: "23462", method: "POST", ip: "208.74.35.5" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });

注意:密切关注开发人员工具或 firebug XHR 调试过程是了解更多有关任何技术中的 api 调用的好方法。

【讨论】:

  • 上述我已经尝试过,但它给出了一个错误:禁止(CSRF令牌丢失或不正确。):/viewprofile [07/Jun/2020 15:22:46] "POST /viewprofile HTTP/ 1.1" 403 2513
  • 有两种方法,我会告诉更简单的一种,from django.views.decorators.csrf import csrf_exempt 并在 ajax 调用的函数中添加一个装饰器@csrf_exempt def upload(request, no):
  • 如果问题仍然存在,您可以通过 kiranu941@gmail.com 给我发邮件,或者在此处自行评论。
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
相关资源
最近更新 更多