最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Save array javascript - Stack Overflow

programmeradmin5浏览0评论

I have a long array like this:

var array = [{x: 0, y:0} ...];

Who contains almost 2000 objects. How can I export this to text and use it in another javascript file/project?

I have a long array like this:

var array = [{x: 0, y:0} ...];

Who contains almost 2000 objects. How can I export this to text and use it in another javascript file/project?

Share asked Apr 9, 2015 at 9:21 HieroHiero 2,2057 gold badges30 silver badges48 bronze badges 2
  • Write it to a file on the server with PHP? – Jeremy Thille Commented Apr 9, 2015 at 9:23
  • Convert it to JSON,stackoverflow./questions/2295496/convert-array-to-json – Low Flying Pelican Commented Apr 9, 2015 at 9:24
Add a ment  | 

3 Answers 3

Reset to default 8

Try like this

var array = [{
    x: 0,
    y: 0
}];
var a = document.body.appendChild(
    document.createElement("a")
);
a.download = "export.txt";
a.href = "data:text/plain;base64," + btoa(JSON.stringify(array));
a.innerHTML = "download example text";

Use JSON.stringify(array). This will return you with a string that you can save somewhere, say, on the server, and then re-use it as javascript array again.

To send the string to a server, you can use jQuery's $.ajax function. To retrieve it back, you can again use the $.ajax function, but it might be a good idea to also specify that the result from server is of type json. To do that, specify dataType to be json in the function.

Stringify it and copy it to another JavaScript project

JSON.stringify(array);
发布评论

评论列表(0)

  1. 暂无评论