Javascript 如何在不解析的情况下在javascript中同步包含JSON数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4116992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to include JSON data in javascript synchronously without parsing?
提问by Paull
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.
我想从我自己的服务器加载一个包含数组的 JSON 文件到一个 javascript 对象变量中。
我想在页面加载开始时以同步方式进行,因为页面加载期间需要数据。
I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.
我设法使用 jQuery.getJSON 但这是异步 ajax,它似乎有点矫枉过正。
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>
)
有没有办法以同步方式加载 JSON 而无需自己进行解析?
(或多或少像使用 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
预先感谢您的任何帮助,希望它有意义,因为我是 javascript 新手。保罗
回答by Alex Wayne
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.
getJSON()
只是ajax()
带有dataType:'json'
集合的函数的简写。该ajax()
功能将让您自定义很多关于请求。
$.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.
您仍然使用 with 回调,async:false
但它会在从 ajax 调用继续执行之前触发。
回答by Boris Hamanov
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)
{
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 ;)
注意:此代码仅适用于现代浏览器 - IE8、FF、Chrome、Opera、Safari。对于过时的 IE 版本,您必须使用 ActiveX,如果您愿意,请告诉我,我会告诉您如何使用 ;)
回答by zzzzBov
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.
这将允许您同步使用数据,而不是尝试异步使用 AJAX。
Otherwise you'll have to wait for the AJAX callback before continuing on with whatever it is you're doing.
否则你将不得不等待 AJAX 回调,然后才能继续你正在做的事情。
回答by user2091857
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格式提供的小输入文件并提取少量数据。这在以下情况下工作得很好:
json file is in the same directory as the script and is called data.json, it looks something like this:
json 文件与脚本位于同一目录中,名为 data.json,它看起来像这样:
{"outlets":[
{
"name":"John Smith",
"address":"some street, some town",
"type":"restaurant"
},
..etc...
read the data into js like this:
像这样将数据读入js:
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...
}
回答by smets.kevin
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.
如果 RequireJS 是一个选项,您可以使用 requirejs 使其成为依赖项。我用它来模拟我的 Angular 应用程序中的数据。一些模拟数据在应用程序启动之前就已经存在是很重要的。
//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
只需将 json 数据包装在定义中并将其声明为依赖项。更多信息在这里:http: //requirejs.org/docs/api.html#defsimple
回答by james-geldart
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:
由于潜在的性能问题,AFAIK jQuery 已弃用同步 XHR 请求。您可以尝试将您的应用程序代码包装在 XHR 响应处理程序中,如下所示:
$(document).ready(function() {
$.get('/path/to/json/resource', function(response) {
//'response' now contains your data
//your app code goes here
//...
});
});
回答by user6371909
The modern HTML5 way without jQuery would be:
没有 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)