开发者

Javascript + jQuery UI: After externalizing a JSON variable to a file, how to read the value back?

I'm quite a beginner in JS and even more in jQuery UI. I don't understand if my problem has a very simple synchronous solution, or if I need to write callback functions to cope with something that cannot be anything else than asynchronous...

I had this in a script associated with an HTML document:

var json = "[{ ... some object ... }]"

As the JSON object must be changed, I've created a text file and moved the value into it. Now I've to read the value from the file to assign it to the variable.

I see that when in production, the HTML page will be served by an HTTP server, and the file must be remotely retrieved using HTTP on the server. But also that if I want to test the page on my development machine, with no server, this is just reading a local file.

Is th开发者_JS百科ere a single piece of code that can read the JSON value in both situation, in a synchronous mode, so that something like this would be possible:

var json = ... piece of code...

I initially thought using:

$.getJSON("file.json", function(obj) { json = obj; });

expecting a read error would lead to json variable being the empty or null, but it seems the call is asynchronous and requires more code in callback functions.

Any guidance appreciated.


First of all, the call definitely should be synchronous. Just move the rest of your code into the callback, it's not that hard - and it will make your browser responsive while the file is downloaded.

If this is really a big problem, you can use the async option in $.ajax:

$.ajax({
  async: false,
  url: 'file.json',
  dataType: 'json',
  success: function (value) { json = value; }
});

Note: This will only work if the file you're requesting is from the same domain, and may or may not fail for local files, depending on the browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜