繁体   English   中英

jQuery-AJAX:检查数据是否存在,如果不存在“ POST”

[英]jQuery-AJAX: Checking if Data Exists, if not “POST”

我正在尝试检查在“ 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

看起来这很完美!

var match = false;
$.each(naming, function(i,v){
  if(v.name == name){
         match = true;
        return false;
    }
 });
 if(!match){
  POST(section);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM