2017-07-04 61 views
-1

我想輸入一些東西到輸入字段中,然後從API獲取響應(如果值存在與否)。使用jQuery獲取API的響應

如果郵政編碼(12345)存在,API將以真/假值進行響應。 http://192.168.100.100:8887/public?zipcode=12345

而且這裏是我到目前爲止的代碼:

$(function() { 

    $('.positiveMessage, .negativeMessage').hide() 
    $('#submitBtn').on('click', function() { 
     var $zipcode = document.getElementById('searchZipCode').value 
     $.getJSON({ 
      type: 'GET', 
      url: 'http://192.168.100.100:8887/public?zipcode=' + $zipCode, 
      success: result => { 
       //Goes through the array 
       $.each(result, function(i, info) { 
        $('body').append(info + '') 
       }) 
      } 
     }) 
    }) 
}) 

正如你看到的,我想通過在鏈接中加入一個變量來操縱API。

+2

你給一個本地IP;) –

+1

行動!我會寫出JSON! –

+0

你正在循環布爾? –

回答

1

我加了一個簡單的if else語句,結果沒問題。雖然我不知道我是否應該用這個方法還是不:

//Checks keys 
if (result) { 
    $('.positiveMessage').show() 
} else { 
    $('.negativeMessage').show() 
} 
+0

是的,這是一個比循環布爾值更好的解決方案 –

+0

好吧!謝謝你這麼快答覆彼得。對此,我真的非常感激。順便說一句,當我搜索一個不存在的值時,我的'.negativeMessage'顯示出來,但是當我搜索一個能退出我的'.positiveMessage'的值時,我的其他消息也不會消失。有什麼想法嗎? –

1

你已經有了一些ES6在那裏(在你成功的功能左箭頭)如你期待的,可能無法正常工作。當你已經有jQuery時,你也使用getElementById。

沒有API提要很難回答,但這應該會幫助您至少得到回覆。使用console.log打印API返回的內容,然後您應該能夠遍歷所需的數據。

$(function() { 
 
    $('.positiveMessage, .negativeMessage').hide() 
 
    $('#submitBtn').on('click', function() { 
 
     var zipCode = $('#searchZipCode').val(); 
 
     $.getJSON({ 
 
      type: 'GET', 
 
      url: 'http://192.168.100.100:8887/public?zipcode=' + zipCode, 
 
      success: function(result){ 
 
       if (result) { 
 
        $('.positiveMessage').show() 
 
        $('.negativeMessage').hide() 
 
       } else { 
 
        $('.positiveMessage').hide() 
 
        $('.negativeMessage').show() 
 
       } 
 
      } 
 
     }) 
 
    }) 
 
})

0

您可以使用這一招:

$('.positiveMessage').show(); 
var time_hide = 1000; // in ms 
setTimeout(function(){ 
    $('.positiveMessage').hide(); 
}, time_hide); 
+0

聰明的想法,但我不知道,如果一個組件持續到用戶再次搜索我更好。 *思維面孔* –