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

时间:2015-07-17 05:56:30

标签: javascript jquery arrays ajax json

我正在尝试检查数据是否已存在于' GET'中返回的JSON数组对象中。如果数据已经存在,我希望它忽略数据。如果它不存在我想要它" POST。"请帮忙。它似乎正在跳过" 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


}

2 个答案:

答案 0 :(得分:1)

从此处删除!

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

所以你有:

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

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

答案 1 :(得分:0)

看起来这个效果非常好!!

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