Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:如何从文件加载UI消息?_Javascript - Fatal编程技术网

JavaScript:如何从文件加载UI消息?

JavaScript:如何从文件加载UI消息?,javascript,Javascript,我对JS非常陌生,所以这可能是一个简单的问题,但我还没有真正找到解决方案。我正在用JS构建几个HTML表单,其中包含用户界面消息,如标题、占位符等。我不想硬编码这些,而是从文件中加载它们(尽管我不需要完整的国际化框架)。在PHP中,我只需执行类似于$msg=parse_ini_file(“messages.ini”)的操作,然后作为$msg[“form_title”]访问它们 JS中的等效过程是什么?您可以在JSON文件中定义所有消息,并使用ajax请求从UI在初始化过程中将它们加载到local

我对JS非常陌生,所以这可能是一个简单的问题,但我还没有真正找到解决方案。我正在用JS构建几个HTML表单,其中包含用户界面消息,如标题、占位符等。我不想硬编码这些,而是从文件中加载它们(尽管我不需要完整的国际化框架)。在PHP中,我只需执行类似于
$msg=parse_ini_file(“messages.ini”)
的操作,然后作为
$msg[“form_title”]
访问它们


JS中的等效过程是什么?

您可以在JSON文件中定义所有消息,并使用ajax请求从UI在初始化过程中将它们加载到localstorage/sessionstorage中。 您可以轻松地从localstorage访问数据,如
localStorage.getItem(form_title)

因为JS是在浏览器中运行的,而PHP是在服务器上运行的,所以您需要发出get请求来“获取”信息。我倾向于使用fetch,因为它正在成为一种标准

因此,您可以使用JSON格式的纯文本文件中的数据,也可以使用类似node/express的后端来提供数据

带有承诺的典型提取请求如下所示:

fetch(
   'http://www.somedomain.com/somedata.json',
   {method: 'GET'}
)
.then((response) => response.json())
.then((json) => {console.log(json.form_title););
$(".tofill").load("content.html .filler");

您应该使用jQuery.load函数

如果需要,您只能加载文件的一部分

假设您的div位于index.html中,就像

<div class="tofill">Fill me</div>
<div class="filler">This is the filling text</div>
您还可以使用load函数中的选择器仅获取所需内容,如下所示:

fetch(
   'http://www.somedomain.com/somedata.json',
   {method: 'GET'}
)
.then((response) => response.json())
.then((json) => {console.log(json.form_title););
$(".tofill").load("content.html .filler");
更进一步,你只能像这样抓取filler div里面的东西

$(".tofill").load("content.html .filler > *");

谢谢,看起来真的很有趣。我会试试看。