2016-11-17 63 views
0
function wrong(word){ 

$("#main-display").html(""); 
$("#main-display").append("Sorry that is not a valid word"); 


var word = "lighht"; 
var check = "https://montanaflynn-spellcheck.p.mashape.com/check/?text=" + word; 

// Ajax request to wordsapi 
// Will return the synonyms of the searched word 
$.ajax({ 
    url: check, // The URL to the API. You can get this in the API page of the API you intend to consume 
    type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc 
    data: {}, // Additional parameters here 
    dataType: 'json', 
    success: function(data) { console.dir((data.source)); console.log(data);}, 
    error: function(err) { wrong(word) }, 
    beforeSend: function(xhr) { 
    console.log(check); 
    xhr.setRequestHeader("X-Mashape-Authorization", "key"); // Enter here your Mashape key 
    } 



}).done(function(response){ 
    console.log(word); 
    console.log(response); 
    var hey = Object.keys(response.corrections); 
    console.log(hey); 
    console.log(response.corrections +".lighht"); 
    for (var i = 0; i < 10; i++) { 
     console.log(Object.keys(response.corrections.lighht)); 
    } 

}); // End of ajax of synonyms 

所以我想做一個函數,返回基於用戶輸入的單詞可能的選擇。我發現了一個效果很好的API,但我很難在屏幕上獲取它的數據。 JSON對象如下所示:JavaScript,我正在做一個AJAX請求,我需要通過對象的幫助

我遇到的主要問題是「lighht」的對象鍵將根據單詞進行更改。因此,當我嘗試使其變成如下形式時:

{ 
    "original": "lighht", 
    "suggestion": "light", 
    "corrections": { 
    "lighht": [ 
     "light", 
     "sleight", 
     "hightail", 
     "alright", 
     "Bligh", 
     "Lhotse", 
     "Galahad" 
    ] 
    } 
} 

console.log(Object.keys(response.corrections.word[i])); 

它不工作並且中斷。

所以我需要知道如何獲得這些數據。

+3

'corrections'不哈有一個屬性叫'字' –

+0

我知道,但它需要它作爲用戶選擇的可變基礎 – heybit

回答

1

您正在使用jQuery的,所以你可以只使用$.each()

var response = { 
 
    "original": "lighht", 
 
    "suggestion": "light", 
 
    "corrections": { 
 
    "lighht": [ 
 
     "light", 
 
     "sleight", 
 
     "hightail", 
 
     "alright", 
 
     "Bligh", 
 
     "Lhotse", 
 
     "Galahad" 
 
    ], 
 
    "cooool": [ 
 
     "cool", 
 
     "car" 
 
    ] 
 
    } 
 
}; 
 

 
// If you want to iterate over all of the corrections: 
 
$.each(response.corrections, function(c) { 
 
    console.log(response.corrections[c]); 
 
}); 
 

 
var userInput = 'cooool'; 
 

 
// Access an individual item: 
 
console.log(response.corrections[userInput]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

非常感謝! – heybit

0

使用循環

var response = { 
 
    "original": "lighht", 
 
    "suggestion": "light", 
 
    "corrections": { 
 
    "lighht": [ 
 
     "light", 
 
     "sleight", 
 
     "hightail", 
 
     "alright", 
 
     "Bligh", 
 
     "Lhotse", 
 
     "Galahad" 
 
    ] 
 
    } 
 
} 
 

 

 
$.each(response.corrections, function(v) { 
 
     console.log(v); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

我不認爲更正是一個數組。 –