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