【问题标题】:jQuery datatables plugin databinding with stringjQuery datatables 插件数据绑定与字符串
【发布时间】:2013-10-01 06:21:06
【问题描述】:

我的服务收到 JSON 响应。按照教程,我在 datatables jquery 插件中创建了绑定数据的响应。

客户端代码:

var test_reports = jsonResp.reports;
var aDataSet = [test_reports];

$('#example').dataTable( {
    "aaData": aDataSet,
    "aoColumns": [{ "sTitle": "Tests" },
          { "sTitle": "Reports"}]
});

在控制台中,我的“test_reports”显示:

['TEST_1','1'] ['TEST_2','1']

但是在将此数据绑定到表时,它会引发错误。如果我将此 cosole 输出复制到 aaData,它会创建表。我知道我的“test_reports”是一个字符串,这个插件需要一个值数组。让这项工作有任何想法!

服务器端代码,它给出了这个 json 响应:

testcasesCountRS = statement.executeQuery(testcasesQuery);

            while(testcasesCountRS.next()){
                String test_name = testcasesCountRS.getString("test_name");
                String test_count = testcasesCountRS.getString("test_count");
                testResults.put(test_name, test_count);
                resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
            }

resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));

reports.put("reports", resBuffer);

在我的服务器端代码中是否有任何替代方法可以将响应作为数组对象发送到数据表插件。

【问题讨论】:

    标签: javascript jquery json datatables


    【解决方案1】:

    你的服务器响应应该是一个数组。

    [['TEST_1','1'],['TEST_2','1']]

    将您的代码更改为

    resBuffer.append("[");
    while(testcasesCountRS.next()){
        String test_name = testcasesCountRS.getString("test_name");
        String test_count = testcasesCountRS.getString("test_count");
        testResults.put(test_name, test_count);
        resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
    }
    resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));
    resBuffer.append("]");
    

    以上代码未经测试。但希望你明白这一点。

    Documentation link

    【讨论】:

    • 感谢bhb的回答。这里的问题是当我在字符串上下文中使用它时,它会将响应作为字符串本身发送。但我应该使用 JSONArray 并发送响应。
    【解决方案2】:

    我通过以下方式使其工作:

    JSONArray testCaseArray = new JSONArray();
    while(testcasesCountRS.next()){
                    JSONArray testCase = new JSONArray();
                    String test_name = testcasesCountRS.getString("test_name");
                    String test_count = testcasesCountRS.getString("test_count");
    
                    testCase.add(test_name);
                    testCase.add(test_count);
                    testCaseArray.add(testCase);
    }
    
    reports.put("reports", testCaseArray);
    

    唯一困扰我的是,它的代码太愚蠢了,以至于我每次都需要在循环中创建一个新数组。并将这些数组添加到我的主 Array 对象中。应该有一些解决方法使它变得简单。请提出一些有效的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2014-11-07
      • 2010-12-13
      相关资源
      最近更新 更多