合并JSON字符串以简化AJAX

时间:2013-04-07 20:04:34

标签: jquery ajax json html5 web-sql

我目前有以下代码来处理Web SQL行。目前,它向服务器发送每行请求。我想以某种方式将所有行合并到一个多维JSON对象中,但我似乎无法找到有关如何执行此操作的任何文档。

当我遍历结果时,有什么方法可以“追加”对象吗?

$("#sync-surveys").click(function(){
$.mobile.showPageLoadingMsg();
db.transaction(function(tx) {
    tx.executeSql("SELECT * FROM surveys", [], function(tx, result) {           
    for (var i = 0, item = null; i < result.rows.length; i++) {
        item = result.rows.item(i);
        var json_str = JSON.stringify(item);

        $.ajax({
            type: "post", url: "/survey/survey/process_survey",
            data: json_str,
            success: function (data) {
                alert("saved successfully");
                $.mobile.hidePageLoadingMsg();
            },
            error: function (data) {
                alert(data.responseText);
                $.mobile.hidePageLoadingMsg();
                //console.log(data);
            }
        });//End ajax function
    }//End results loop


    });
});//End Transaction

});//End Surveys Click

1 个答案:

答案 0 :(得分:0)

不要“合并字符串”。相反,“构建图表”。

// build data-structure / object graph - alter as required
// make sure to choose something easy to consume/extend.
var items = [];
for (var i = 0; i < result.rows.length; i++) {
        var item = result.rows.item(i);
        // maybe do something else here? if not, it might be possible
        // to JSON.stringify result.rows directly and/or use Array.slice
        // to avoid this loop entirely
        items.push(item);
}
// send request - only build JSON from JS object graph once at end
// JSON = text: modify graph before converting for transmission
$.ajax({
   data: JSON.stringify(items),
   ..
});