【问题标题】:Jquery: Unable to add Json object to Ajax requestJquery:无法将 Json 对象添加到 Ajax 请求
【发布时间】:2015-07-13 12:01:18
【问题描述】:

Overview:我正在制作一个网络工具,使用图表(Highcharts)在数字平台上显示不同工作室销售的电影总数。这些图表是动态的,因此用户可以使用一系列过滤器来更改结果。

Filter 1 - Studios: 使用此过滤器,用户可以选择他希望看到其销售的不同工作室。

Filter 2 - Period: 这是他希望看到销售的持续时间。 正是这个过滤器给了我问题。

基本上,周期的选择不会随 AJAX 请求一起发送,因此对图表没有影响。周期的默认值(使用 momentjs 库设置)也与 AJAX 请求一起使用。没有添加到请求中的是期间的更改。

没有这样的错误信息。

代码:

$(document).ready(function(){

var btnStudiosDiv = $('#btnStudios');

var getStudios = function () 
// Get all studio's from buttons with .active class               
var studios = $('button.active', btnStudiosDiv).map(function () {
    return $(this).val();
}).get();

// If no studio's found, get studio's from any button.
if (!studios || studios.length <= 0) {
    studios = $('button', btnStudiosDiv).map(function () {
        return $(this).val();
    }).get();
}

return studios;
};



var periodFrom = (moment().format('WW')-11)
var periodTo = moment().format('WW')
var output = {};

var show = function (studios) {
output['Studios'] = studios,

var per = {Period: {"From":["W" + periodFrom],"To":["W" + periodTo]}};
$.extend(output, per);
$('.list').html(JSON.stringify(output)); //Display Json Object on the Webpage

$.ajax({  //Ajax call to send the Json string to the server

        type: "POST", 
        data: {"jsontring": JSON.stringify(output)},
        url: "http://localhost:8080/salesvolume" ,
        contentType: "application/json",
        dataType: "json",
        cache: false,
        beforeSend: function() {
        $('#container').html("<img class = 'ajload' src='loading.gif' />");
         },

        success: function(data){
                                alert(  )   ;
                                $('#container').highcharts(data);
                                },
        error: function() {
                            alert("Something is not OK :(") 
                                },

        }); 





};

var timer; //To create a time delay of 2 Secs for every selection
$(".btn").click(function () {


$(this).toggleClass('active');
// Fetch studios
var studios = getStudios();


// Remove previous timeOut if it hasn't executed yet.

if(timer)
    clearTimeout(timer);

// Wait 2 sec
timer = setTimeout(function () {
    // Fill list with the studios
    show(studios);
},2000);


});

// Show the json on page load
show(getStudios());






//Period Selector (Template used from http://jqueryui.com/datepicker/)
$(function() {
var startDate;
var endDate;  
var selectCurrentWeek = function() {
    window.setTimeout(function () {
        $('#weekpickerFrom').datepicker('widget').find('.ui-datepicker-current-day a').addClass('ui-state-active')
    }, 1);
}

$('#weekpickerFrom').datepicker( {
  showOn: "button",
  buttonImage: "calendar2.gif",
  buttonImageOnly: true,
  buttonText: "Select date",
    changeMonth: true,
    changeYear: true,
    showWeek: true,
    showOtherMonths: false,
    selectOtherMonths: false,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate');
        startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
        endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
        var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
        $('#weekpickerFrom').val(date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
        output.Period.From = (date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
        periodFrom = output.Period.From //Add Period from to the Json String
        if(timer)
        clearTimeout(timer);
        timer = window.setTimeout(function() {$('.list').html(JSON.stringify(output))},2000); //Display Json Object on the Webpage



        selectCurrentWeek();
    },
    beforeShow: function() {
        selectCurrentWeek();
    },
    beforeShowDay: function(date) {
        var cssClass = '';
        if(date >= startDate && date <= endDate)
            cssClass = 'ui-datepicker-current-day';
        return [true, cssClass];
    },
    onChangeMonthYear: function(year, month, inst) {
        selectCurrentWeek();
    }
}).datepicker('widget').addClass('ui-weekpickerFrom');




$('.ui-weekpickerFrom .ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.ui-weekpickerFrom .ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});

$(function() {
var startDate;
var endDate;  
var selectCurrentWeek = function() {
    window.setTimeout(function () {
        $('#weekpickerTo').datepicker('widget').find('.ui-datepicker-current-day a').addClass('ui-state-active')
    }, 1);
}

$('#weekpickerTo').datepicker( {
    showOn: "button",
    buttonImage: "calendar2.gif",
    buttonImageOnly: true,
    buttonText: "Select date",
    changeMonth: true,
    changeYear: true,
    showWeek: true,
    showOtherMonths: false,
    selectOtherMonths: false,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate');
        startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
        endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
        var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
        $('#weekpickerTo').val(date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
        output.Period.To = (date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
        periodTo = output.Period.From //Add Period to to the Json String
        if(timer)
        clearTimeout(timer);
        timer = window.setTimeout(function() {$('.list').html(JSON.stringify(output))},2000); //Display Json Object on the Webpage


        selectCurrentWeek();
    },
    beforeShow: function() {
        selectCurrentWeek();
    },
    beforeShowDay: function(date) {
        var cssClass = '';
        if(date >= startDate && date <= endDate)
            cssClass = 'ui-datepicker-current-day';
        return [true, cssClass];
    },
    onChangeMonthYear: function(year, month, inst) {
        selectCurrentWeek();
    }
}).datepicker('widget').addClass('ui-weekpickerTo');

$('.ui-weekpickerTo .ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.ui-weekpickerTo .ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });


});





});     

如果有人能指出我哪里出错了,那将非常有帮助。

Note:该工具上添加了多个其他过滤器,但为简单起见,1 只提到了两个重要的。

【问题讨论】:

  • 那么,你的 $.extend() 之后的“输出”是什么样的?它有正确的数据和格式吗?如果是这样,那么接收器呢?是否正确解析?
  • 你试过用:$.post("url", { jsonstring: JSON.stringify(output) }, function(data) { //actions with data console.log(data); }, "json");

标签: javascript jquery ajax json highcharts


【解决方案1】:

我觉得数据应该是这样的

$.ajax({
        type: "POST", 
        **data: "{\"jsontring\":" + JSON.stringify(output) + "}",**
        url: "http://localhost:8080/salesvolume" ,
        contentType: "application/json",
        dataType: "json",
        cache: false,
        beforeSend: function() {
        $('#container').html("<img class = 'ajload' src='loading.gif' />");
         },

        success: function(data){
                                alert(  )   ;
                                $('#container').highcharts(data);
                                },
        error: function() {
                            alert("Something is not OK :(") 
                                },

        });

在您的 Ajax 请求中

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 2013-12-12
    • 2015-09-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多