JavaScript,我正在做一个ajax请求,我需要通过对象的帮助
JavaScript, I am making an ajax request and I need help going through the object
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对象看起来像这样:
我遇到的主要问题是"light"的对象键将根据单词而变化。所以当我把它变成一个变量,比如:
{
"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>
使用循环
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>
相关文章:
- servlet中的请求对象,而不是从jsp接收参数值
- 哪个 JavaScript 库在请求对象上设置 _parsedUrl 属性
- 从express请求对象获取客户端MAC地址
- 请求对象中的MEANJS猫鼬模型
- 我的 AJAX 请求对象无法正确解析 URL 的协议部分
- ajax - 请求对象就绪状态不变
- 使用请求对象中可用的值打印 JavaScript 警报
- backbone.js中.save()的响应/请求对象
- 是否可以在另一个后置请求中转发一个后置请求对象
- 节点.js请求对象 - 返回响应正文以供进一步操作
- 如何从节点.js请求对象读取数据事件(块)
- Nodejs,Express - 尝试从请求对象获取客户端 IP - 显示 127.0.0.1
- 超级代理“请求”对象被重新定义为函数
- 检查 parse.com 请求对象
- 如何在 angularjs 中删除请求对象中的文件
- 如何测试方向的相等性服务请求对象
- 从 grunt-contrib-connect 请求对象获取数据
- 如何使用不同的URL复制请求对象
- 在不覆盖用户请求对象的情况下,使用具有多种策略的passport.js
- 为什么我的请求对象没有方法“param”