如何在javascript中同步包含JSON数据而不进行解析?

发布于 2024-10-01 04:11:52 字数 344 浏览 0 评论 0原文


我想从我自己的服务器加载一个包含数组的 JSON 文件到 javascript 对象变量中。
我想在页面加载开始时以同步方式执行此操作,因为页面加载期间需要数据。

我设法使用 jQuery.getJSON,但这是异步 ajax,它似乎有点矫枉过正。

有没有一种方法可以以同步方式加载 JSON,而无需自己进行解析?
(或多或少类似于使用

预先感谢您的任何帮助,希望它有意义,因为我是一个 javascript 新手。 保罗

I want to load a JSON file from my own server containing an array into a javascript Object variable.
I would like to do it at the beginning of page load in a synchronous way because data is needed during page load.

I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.

Is there a way to load JSON in a synch way without doing your own parsing?
(more or less like using a <script language="JavaScript" src="MyArray.json"></script>)

Thanks in advance for any help, hope it makes sense since I am a javascript newbie.
Paolo

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

森末i 2024-10-08 04:11:52

getJSON() 只是设置了 dataType:'json'ajax() 函数的简写。 ajax() 函数可以让您自定义很多有关请求的内容。

$.ajax({
  url: 'MyArray.json',
  async: false,
  dataType: 'json',
  success: function (response) {
    // do stuff with response.
  }
});

您仍然使用带有 async:false 的回调,但它会在 ajax 调用继续执行之前触发。

getJSON() is simply shorthand for the ajax() function with the dataType:'json' set. The ajax() function will let you customize a lot about the request.

$.ajax({
  url: 'MyArray.json',
  async: false,
  dataType: 'json',
  success: function (response) {
    // do stuff with response.
  }
});

You still use a callback with async:false but it fires before it execution continues on from the ajax call.

仅此而已 2024-10-08 04:11:52

给你:

// Load JSON text from server hosted file and return JSON parsed object
function loadJSON(filePath) {
  // Load json file;
  var json = loadTextFileAjaxSync(filePath, "application/json");
  // Parse json
  return JSON.parse(json);
}   

// Load text with Ajax synchronously: takes path to file and optional MIME type
function loadTextFileAjaxSync(filePath, mimeType)
{
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.open("GET",filePath,false);
  if (mimeType != null) {
    if (xmlhttp.overrideMimeType) {
      xmlhttp.overrideMimeType(mimeType);
    }
  }
  xmlhttp.send();
  if (xmlhttp.status==200 && xmlhttp.readyState == 4 )
  {
    return xmlhttp.responseText;
  }
  else {
    // TODO Throw exception
    return null;
  }
}

注意:此代码仅适用于现代浏览器 - IE8、FF、Chrome、Opera、Safari。对于过时的 IE 版本,您必须使用 ActiveX,如果您需要,请告诉我,我会告诉您如何操作;)

Here you go:

// Load JSON text from server hosted file and return JSON parsed object
function loadJSON(filePath) {
  // Load json file;
  var json = loadTextFileAjaxSync(filePath, "application/json");
  // Parse json
  return JSON.parse(json);
}   

// Load text with Ajax synchronously: takes path to file and optional MIME type
function loadTextFileAjaxSync(filePath, mimeType)
{
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.open("GET",filePath,false);
  if (mimeType != null) {
    if (xmlhttp.overrideMimeType) {
      xmlhttp.overrideMimeType(mimeType);
    }
  }
  xmlhttp.send();
  if (xmlhttp.status==200 && xmlhttp.readyState == 4 )
  {
    return xmlhttp.responseText;
  }
  else {
    // TODO Throw exception
    return null;
  }
}

NOTE: This code works in modern browsers only - IE8, FF, Chrome, Opera, Safari. For obosolete IE versions you must use ActiveX, let me know if you want that I will tell you how ;)

慵挽 2024-10-08 04:11:52

如果您使用某种服务器脚本,则可以将数据打印到页面上的脚本标记:

<script type="text/javascript">
var settings = <?php echo $json; ?>;
</script>

这将允许您同步使用数据,而不是尝试异步使用 AJAX。

否则,您必须等待 AJAX 回调才能继续您正在执行的操作。

if you're using a server script of some sort, you could print the data to a script tag on the page:

<script type="text/javascript">
var settings = <?php echo $json; ?>;
</script>

This will allow you to use your data synchronously rather than trying to use AJAX asynchronously.

Otherwise you'll have to wait for the AJAX callback before continuing on with whatever it is you're doing.

安人多梦 2024-10-08 04:11:52

我只需要读取一个以 json 格式提供的小输入文件并提取少量数据。这在这种情况下工作得很好:

json 文件与脚本位于同一目录中,称为 data.json,它看起来像这样:

{"outlets":[
        {
            "name":"John Smith",
            "address":"some street, some town",
            "type":"restaurant"
        },
..etc...

将数据读入 js,如下所示:

var data = <?php echo require_once('data.json'); ?>; 

访问数据项如下:

for (var i in data.outlets) {    
var name = data.outlets[i].name;
... do some other stuff...
}

I only needed to read a small input file provided in json format and extract a small amount of data. This worked just fine in the circumstances:

json file is in the same directory as the script and is called data.json, it looks something like this:

{"outlets":[
        {
            "name":"John Smith",
            "address":"some street, some town",
            "type":"restaurant"
        },
..etc...

read the data into js like this:

var data = <?php echo require_once('data.json'); ?>; 

Access the data items like this:

for (var i in data.outlets) {    
var name = data.outlets[i].name;
... do some other stuff...
}
≈。彩虹 2024-10-08 04:11:52

如果 RequireJS 是一个选项,您可以使用 requirejs 将其设为依赖项。我用它来模拟 Angular 应用程序中的数据。在应用程序引导之前,一些模拟数据必须存在,这一点至关重要。

//Inside file my/shirt.js:
define({
    color: "black",
    size: "unisize"
});

只需将 json 数据包装在定义中并将其声明为依赖项即可。更多信息请参见:http://requirejs.org/docs/api.html#defsimple

If RequireJS is an option, you can make it a dependency using requirejs. I use it to mock data in my Angular application. It's essential that some of the mocked data is there before the bootstrap of the app.

//Inside file my/shirt.js:
define({
    color: "black",
    size: "unisize"
});

Just wrap the json data in a define and declare it as a dependency. More info here: http://requirejs.org/docs/api.html#defsimple

为你拒绝所有暧昧 2024-10-08 04:11:52

如果该文件可公开访问,您可以尝试:

let rawdata = require('./path/file.json');

console.log(rawdata); // should be available

If the file is accessible publicly, you could try:

let rawdata = require('./path/file.json');

console.log(rawdata); // should be available
月下凄凉 2024-10-08 04:11:52

据我所知,由于潜在的性能问题,jQuery 已弃用同步 XHR 请求。您可以尝试将应用程序代码包装在 XHR 响应处理程序中,如下所示:

$(document).ready(function() {
  $.get('/path/to/json/resource', function(response) {
    //'response' now contains your data
    //your app code goes here
    //...
  });
});

AFAIK jQuery has deprecated synchronous XHR requests because of the potential for performance issues. You could try wrapping your app code up in the XHR response handler as in the following:

$(document).ready(function() {
  $.get('/path/to/json/resource', function(response) {
    //'response' now contains your data
    //your app code goes here
    //...
  });
});
你如我软肋 2024-10-08 04:11:52

没有 jQuery 的现代 HTML5 方式是:

   var url="https://api.myjson.com/bins/1hk8lu" || "my.json"
   var ok=await fetch(url)
   var json=await ok.json()
   alert(a.test)

The modern HTML5 way without jQuery would be:

   var url="https://api.myjson.com/bins/1hk8lu" || "my.json"
   var ok=await fetch(url)
   var json=await ok.json()
   alert(a.test)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文