【问题标题】:Django: problem with format when using ajax query (string/Json)Django:使用 ajax 查询(字符串/Json)时出现格式问题
【发布时间】:2020-08-11 00:26:08
【问题描述】:

我尝试使用 ajax 发送数据,但格式是字符串,我需要 JSON(或格式化数据)

要发送的数据显示在 HTML 表格中。 我在所有行中循环以收集要使用 ajax 发送的所有数据。 但是当我在使用 JSON.Parse(new_parameters) 时尝试创建 JSON 对象时出现错误。 如果在我的 ajax 查询中使用 new_parameters,我会在我的 ajax 视图中得到 False ... 如果我“字符串化”new_parameters 以在我的 ajax 查询中使用它,我会在我的 ajax 视图中获取数据,但以字符串格式...... 这意味着我构造 new_parameters 的方式不是一个好方法......

    var parameters = {};
    var current_parameters = [];
    var new_parameters = [];

    // Collect data from html data when user click on "Modify settings" button
    $(document).on('click', '#modifier', function(event) 
    {
        event.preventDefault(); 
        $('#table_parametrage tr').each(function() {

            var parameter = {};
            $(this).find('td div').each (function() {

                parameter[$(this).attr("col_name")] = $(this).eq(0).html();
            }); 

            new_parameters.push(parameter);  
        });

        new_parameters.shift(); 

        // requête ajax > start
        // parameters = JSON.parse(new_parameters, null, 2);
        console.log(new_parameters);

        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 = cookies[i].trim();
                    // 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');

        $.ajax({
            type: "POST",
            url: $(this).data("ajax-url"),
            data: {
                csrfmiddlewaretoken: csrftoken,
                'data' : new_parameters,
            },
            dataType: 'json',
            success: function (data) {
                // alert(data);
            },
            error : function(resultat, statut, erreur){
                //
            }
        });
        // requête ajax > end

        // Remise à zéro de la liste
        new_parameters = [];
        parameters = {};


    });

【问题讨论】:

    标签: javascript jquery json django


    【解决方案1】:

    对于那些感兴趣的人,即使我不确定它是否是最好的代码,我也会这样解决我的问题:

    JS:

    ...
            parameters = JSON.stringify(new_parameters, null, 2);
    
            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 = cookies[i].trim();
                        // 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');
    
            $.ajax({
                type: "POST",
                url: $('#modifier').data("ajax-url"),
                data: {
                    csrfmiddlewaretoken: csrftoken,
                    'data' : parameters,
                },
                dataType: 'json',
                success: function (data) {
                    // alert(data);
                },
                error : function(resultat, statut, erreur){
                    //
                }
            });
    
    
    # requete ajax
    def ajax(request):
        if request.method == "POST":
            data = request.POST.get('data',False)
    
            # https://www.programiz.com/python-programming/json
            data_dict = json.loads(data)
            print(data_dict)
            print(data_dict[0]['ran_st1'])
    
        else:
            datas = ''
            print('echec')
    
        return render(request, 'randomization_settings/ajax.html', {})
    

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多