添加到JSON而不会覆盖(使用Ajax)

时间:2019-08-01 07:43:45

标签: javascript jquery json ajax

首先,我很抱歉是否曾问过这个问题。我一直在搜索几个小时,但找不到最终的答案。

我目前正在使用Google Chrome扩展程序,每当 Chrome用户(已登录)使用该扩展程序时,我都希望该用户的电子邮件地址登录到JSON文件中,用于现在-测试目的,将不使用任何真实帐户)托管在http://myjson.com

为了检索用户的Google帐户,我使用了chrome.identity。那很好。我的问题是我似乎找不到任何方法:

  • 如果用户已经存在,则搜索在线JSON,将整个内容作为JSON字符串/对象检索
  • 将新用户添加到JSON,而无需再次检索整个对象,将其添加到本地,然后覆盖现有对象。

这是我的代码。它的作用就是简单地检索所有JSON,在本地更改我想要的内容,然后基本上将其覆盖。这不是我想要的。

function readApi(){
    if($.isEmptyObject(userObj)) {
        chrome.identity.getProfileUserInfo(function(userInfo) {
            userObj = {id: userInfo.id, email: userInfo.email};
        });
    }

    async function loadJson(url) { // (1)
        let response = await fetch(url); // (2)

        if (response.status === 200) {
            return await response.json(); // (3)
        }

        throw new Error(response.status.toString());
    }

    loadJson('the_url_from_myjson')
        .then((value) => {
            const userInJSON = value.users.find( user => user.id === userObj.id);

            console.log(value);

            if(!userInJSON) {
                let users = value.users;
                users.push(userObj);
                value.users = users;

                $.ajax({
                    url: 'the_url_from_myjson',
                    type: "PUT",
                    data: JSON.stringify(value),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        let json = JSON.stringify(data);
                    }
                })
            }

        })
        .catch(alert); // Error: 404 (4)

    setTimeout(readApi, 5000);
}readApi();

任何帮助将不胜感激。

0 个答案:

没有答案