【问题标题】:Fill select dropdown with JSON file data使用 JSON 文件数据填充选择下拉列表
【发布时间】:2021-01-28 17:27:19
【问题描述】:

我有自己创建的JSON 文件,并想用这些数据填充select>option。但我收到Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/.../policy_app_policytype.json. (Reason: CORS request not http). 我该如何解决?这是我的代码:

index.html:

<div id="insurance-type">
  <select name="insurance-type-select" id="insurance-type-select">
    <option></option>
  </select>
</div>

script.js:

        $(document).ready(function () {
            var url = "policy_app_policytype.json";
            $.getJSON(url, function (data) {
                $.each(data, function (index, value) {
                    $('#insurance-type-select').append('<option value="' + value.id + '">' + value.display_name + '</option>');
                });
            });
        });

json:

[
    {
        "description": "Avtonəqliyyat vasitəsi sahiblərinin mülki məsuliyyətinin icbari sığortası şəhadətnaməsi",
        "display_name": "AVSMMİS",
        "id": 1,
        "insurance_type": 1,
        "is_other": 0,
        "policy_type_id": 1,
        "prefix": null,
        "reasons_id": null,
        "status": null,
        "temp_prefix": null
    },
    {
        "description": "Daşınmaz əmlakın icbari sığortası şəhadətnaməsi",
        "display_name": "DƏİS",
        "id": 2,
        "insurance_type": 1,
        "is_other": 0,
        "policy_type_id": 2,
        "prefix": null,
        "reasons_id": null,
        "status": null,
        "temp_prefix": null
    }
]

【问题讨论】:

    标签: javascript html jquery json ajax


    【解决方案1】:

    CORS 请求可能只使用 HTTPS URL 方案,但请求指定的 URL 是不同类型的。如果 URL 使用 file:/// URL 指定本地文件,则通常会发生这种情况。

    要解决此问题,只需确保在发出涉及 CORS 的请求时使用 HTTPS URL,例如 XMLHttpRequest、Fetch API、Web 字体 (@font-face)、WebGL 纹理和 XSL 样式表。

    但如果您真的想读取本地文件,请使用here 中的一些策略:

    【讨论】:

      猜你喜欢
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      相关资源
      最近更新 更多