首页 > 解决方案 > 如何使用 document.ready ajax 乘以 JSON 文件

问题描述

$("document").ready(
    function () {
        $.getJSON("French.json", function displayFromJson(french) {

            console.log(french.firstName)

        })
    },
    function () {
        $.getJSON("english.json", function displayFromJson(english) {
            console.log(english.lastName)
        })
    });

法语.json

{
    "firstName": "Merci",
    "lastName": " Claudè"
}

英语.json

{
    "firstName": "Gracias",
    "lastName": "Claude"
}

标签: javascriptjqueryjsonajax

解决方案


首先,您需要调用对象readydocument不是<document>元素。所以传递document给 jQuery,而不是类型选择器"document"

第二:

ready()接受一个且仅一个函数,因此:

  1. 不要使用ready(在您使用的代码中不需要它,因为您没有操作 DOM)
  2. 调用ready两次,每次传递一个函数
  3. 调用ready一次,将两个函数合二为一

$.getJSON("French.json", function displayFromJson(french) {
    console.log(french.firstName)
});
$.getJSON("english.json", function displayFromJson(english) {
    console.log(english.firstName)
});

$(document).ready(function () {
    $.getJSON("French.json", function displayFromJson(french) {
        console.log(french.firstName)
    });
});

$(document).ready(function () {
    $.getJSON("english.json", function displayFromJson(english) {
        console.log(english.firstName)
    });
});

$(document).ready(function () {
    $.getJSON("French.json", function displayFromJson(french) {
        console.log(french.firstName)
    });
    $.getJSON("english.json", function displayFromJson(english) {
        console.log(english.firstName)
    });
});

推荐阅读