JQuery为多个对象解析json

时间:2016-11-25 05:57:23

标签: javascript jquery json

var tdValue = $.parseJSON(getMedicationOrderInstance(freqKey, $.datepicker.formatDate('dd M yy', dateFrom), $.datepicker.formatDate('dd M yy', dateTo)));

这是我的ajax调用,它在json之后返回,我正在尝试解析但是抛出异常

  

抛出异常而未捕获json2.js(503,13)

 {
      "25": [
        "00:00",
        "05:00",
        "10:00",
        "15:00",
        "20:00"
      ],
      "26": [
        "01:00",
        "06:00",
        "11:00",
        "16:00",
        "21:00"
      ],
      "27": [
        "02:00",
        "07:00",
        "12:00",
        "17:00",
        "22:00"
      ]
    }

伙计们请帮忙。它让我头疼。

function getMedicationOrderInstance(key, dateFrom, dateTo) {
    return $.when(
            $.ajax({
                url: 'ajax',
                dataType: 'json',
                data: {
                    cls: ".....MedicationSearchController",
                    mtd: "getFreqDates",
                    ses: SessID,
                    frequencyKey: key,
                    startDate: dateFrom,
                    endDate:dateTo

                }

            })
    ).then(function(data){
        if (data && data.success === true) {

            return data.results;
        } else {
            // alert(data.exception);
        }
    });
}

1 个答案:

答案 0 :(得分:1)

首先,您不需要使用$.parseJSON。只要您设置dataType: 'json'$.ajax就可以为您完成。

  

如果指定了json,则使用jQuery.parseJSON解析响应   在作为对象传递给成功处理程序之前。解析了   JSON对象通过的responseJSON属性可用   jqXHR对象。

您应该能够将$.when保留在getMedicationOrderInstance中,但此处我会稍微简化一下,并返回原始 jqXHR对象。让消费者决定如何处理它。

function getMedicationOrderInstance(key, dateFrom, dateTo) {
    // Return the jqXHR here...
    return $.ajax({
                url: 'ajax',
                dataType: 'json',
                data: {
                    cls: ".....MedicationSearchController",
                    mtd: "getFreqDates",
                    ses: SessID,
                    frequencyKey: key,
                    startDate: dateFrom,
                    endDate:dateTo

                }
            });
}

然后你可以这样做:

var tdValue = {};
// I moved these to separate variables to increase readability only...
var parsedDateFrom = $.datepicker.formatDate('dd M yy', dateFrom);
var parsedDateTo = $.datepicker.formatDate('dd M yy', dateTo);

var defObj = getMedicationOrderInstance(freqKey, parsedDateFrom, parsedDateTo);

// When the call is complete do this.
defObj.then(function(data){
    // If you properly set dataType in the ajax-call you don't need to parse json.
    console.log(data.result);
    tdValue = data.result;

    // or possibly...
    // tdValue = data; 

    alert('done');
});