JavaScript,我正在发出 ajax 请求,我需要帮助浏览该对象

标签 javascript jquery ajax

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 对象如下所示:

我遇到的主要问题是“lightht”的对象键将根据单词而改变。所以当我尝试将其设置为变量时:

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

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

它不起作用并且会损坏。

所以我需要知道如何获取这些数据。

最佳答案

您正在使用 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>

关于JavaScript,我正在发出 ajax 请求,我需要帮助浏览该对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40647386/

相关文章:

javascript - Ajax 不发送文件

javascript - 获取当前已验证用户的名称

php - 通过 javascript 发出警报文本框

javascript - 同步 jQuery 动画

javascript - 图像淡入但覆盖了原来在 div 中的文本

javascript - 如何在 AJAX 验证后使用 jQuery 提交表单?

javascript - 从ajax响应中提取json数据

javascript - Javascript 可以获取文本形式的函数吗?

javascript - JS中按日期排列聊天消息

javascript - 如何使用ckeditore使用ajax发送数据?