1

我正在构建一个应该能够离线工作的应用程序。我正在使用 jQuery Mobile、PHP、MySQL 和 jStorage 以便轻松使用 HTML5 localStorage

我正在尝试找出将数据下载到本地设备 localStorage 并在稍后阶段使用它而不会减慢或崩溃浏览器的最佳方法。

我在 MySQL 表中有大约 5000 条记录(500 Kb 的数据),我需要应用程序下载所有这些数据,以便离线时在第二阶段使用它。

download_script.php 以 JSON 格式返回所有记录,例如

{"1":{"1":{"p_bar":"10.30","v_0":"0.0312207306000000","h_vap":"311.78","p_10c":"99.99"}},"2":{"1":{"p_bar":"10.40","v_0":"0.0309405941000000","h_vap":"311.29","p_10c":"0.00"}},

我想知道是否有任何方法可以优化以下脚本(例如,为了不挂起浏览器,并可能显示正在下载的数据百分比)

$.ajax({
  url: "download_script.php",
  cache: false,
  success: function(big_json_dump){
  $.jStorage.set('some_key', big_json_dump);
 }
});

这种方法可以优化,例如使用 radpidjson 吗?如何更改它以显示下载数据的实时百分比?

4

2 回答 2

1

(You had a good discussion in the comments but the question is left unanswered...)

"in order to not hang the browser" you need to split the data into smaller parts and fetch every part separately (e.g. in a loop). Otherwise, parsing a big chunk of JSON can hang the browser for a few milliseconds. Rapidjson can't help there, because Rapidjson is C++ and the browser talks JavaScript.

"to display the percentage of data" you need to inform the browser's JavaScript about the total amount of parts first. Again, nothing to do with Rapidjson.

There's also JavaScript streaming JSON parsers (like Clarinet) which, theoretically, can parse the large JSON document in chunks. This gives you more control about the parsing, at the cost of much CPU and programming complexity. You'll probably need to introduce a Web Worker or an aritifial moments of inactivity to keep the browser responsive. But if you're using a Web Worker, you can do the standard JSON.parse in there: http://igorminar.github.io/webworker-json-perf/; http://blog.softwareispoetry.com/2013/05/using-web-workers-to-jsonparse-large.html

于 2014-04-04T06:11:10.247 回答
1

Paginate the results and execute $.ajax in a loop:

var total_records = 5000; // get this number to the browser somehow.
var per_page = 75;
var total_pages = Math.floor(total_records / per_page);

for(var i = 0; i < total_pages; i++) {
    $.ajax({
      url: "download_script.php",
      cache: false,
      data: { page: i },
      success: function(big_json_dump){
      $.jStorage.set('some_key', big_json_dump);
     }
    });
}

To paginate in PHP / in your SQL statement:

$page = intval($_GET['page']);
$from = $page * 50;
SELECT * FROM my_table LIMIT $from, 50;
                             ^^     ^^ total records to show
                             record_cursor
于 2014-04-04T06:21:13.210 回答