javascript - 如何从传递给视图的模型访问 javascript 文件中的 json 对象
问题描述
我的数据库中有一个 JSON 对象,其中包含 html。我将对象作为模型的一部分传递给我的视图。我需要访问该对象并在页面的 javascript 文件中读取它。但是,当我尝试将对象分配给我的 html 文件中的全局变量时,我无法在我的 javascript 文件中访问它。
我尝试将对象作为字符串读取,它返回解码后的 html ("page-1":),但我无能为力。如果我调用 @Html.Raw(@Model.CourseContent.ExpectedResult) 它会按预期创建 JSON 对象。但是在我的 javascript 文件中,它被列为未定义。我不知道如何解决这个问题。
@model DataTransferObjects.Models.UserCourseAndContent
<script>
var totalPages = '@Model.CourseContent.TotalPages';
var expectedResults = @HTML.Raw(@Model.CourseContent.ExpectedResult)
</script>
当我使用上面的代码时出现的 json 对象看起来像
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
我希望它是一个实际的 json 字符串,但我得到了一个对象(?),我很困惑如何从中解码 html,然后将生成的 json obejct 转换为要在 javascript 文件中读取的 json 字符串。任何帮助都会很棒!
解决方案
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
// Parse JSON
const parsedJSON = JSON.parse(JSON.stringify(expectedResults));
// Access to properties
const page-1 = parsedJSON['page-1'];
const page-3 = parsedJSON['page-3'];
推荐阅读
- c# - 使用锁定文件限制 c# 程序的并发用户数
- c++ - While 循环采用用户输入而不采用最后输入的值
- php - PHP Str_replace 不适用于 JSON_DECODE
- python - 比较python中的2个csv文件时列表索引超出范围
- javascript - 为什么我的 HTML onload 事件属性在脚本元素中被忽略?
- javascript - 如何在 Angular(模板驱动表单)中添加图像以选择选项字段?
- elasticsearch - ElasticSearch 解释查询以了解正在访问哪些字段
- reactjs - 无法使用 renderHook 调用挂钩回调
- flutter - Flutter:从全局拦截器中排除某些请求的标头(dio)
- javascript - 无法更改 Bootstrap 5 toast 的选项