javascript - jQuery-AJAX : Checking if Data Exists, 如果不是 "POST"

标签 javascript jquery arrays ajax json

我正在尝试检查“GET”返回的 JSON 数组对象中是否已存在数据。如果数据已经存在,我希望它忽略该数据。如果它不存在,我希望它“发布”。请帮忙。它似乎正在跳过“POST”调用。

  function POST(section){
     $.ajax({
        type: 'POST',
        dataType: 'json',
     async : false,
        data: JSON.stringify(section),
        url: '/api/v2/help_center/en-us/categories/200384077/sections.json',
        contentType: "application/json; charset=utf-8",

        headers: {
            "Authorization": "Basic " + btoa(username + ":" + password)
        },// end headers
        success: function (newSection) {
            console.log("Congrats! We have inserted a new section", newSection);

        },
        error: function (xhr, errorText) {
            console.log('Error ' + xhr.responseText);
        }
    })// end AJAX POST
    }

function addNewSection(name, description) {

    var section = { "section": { "position": 2, "name": name, "description": description, "content.translations.name": [{ "locale": "en-us" }] } };

    $.ajax({
        type: 'GET',
        url: '/api/v2/help_center/categories/200384077/sections.json',
        dataType: 'json',
        async : false,
        headers: {
            "Authorization": "Basic" + btoa(username + ":" + password)
        },
        success: function (mySections) {

            var naming = mySections.sections;
            $.each(naming, function (i, result) {
              if( $.inArray(name, result) == -1)
              {
                console.log("This already exists", name);
              } 

                if( !$.inArray(name, result) == -1) {
              POST(section);
              }

            });

        } // end success function
    })// end AJAX GET


}

最佳答案

从中删除 !:

if( !$.inArray(name, result) == -1)

所以你有:

if ($.inArray(name, result) == -1)

你写的基本上是双重否定。当没有找到任何内容时,$.inArray 返回-1。您永远不会将 !$.inArray 一起使用,因为它永远不会返回 false

关于javascript - jQuery-AJAX : Checking if Data Exists, 如果不是 "POST",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469205/

相关文章:

java - 如何从 JSP 文本框中检索数据并在同一页面的 JQuery 警报框中显示数据?

javascript - 从 JavaScript 中的 HTML 对象获取计算事件

arrays - 如何使用vba在逗号之间分割字符串并将每个字符串存储在数组变量中

php - 多维数组更改键值对

javascript - CSS 边界中断

c# - 从 javascript 渲染的页面获取 HTML 内容

javascript - 推荐有关现代 CSS 和设计实践的好书/资源

javascript - 匹配后查找下一个单词的正则表达式

javascript - 提交后刷新整个页面(Fancybox)

javascript - 在 Javascript 中初始化嵌套关联数组