I have the following function, which currently just displays the object returned from the GET request to the console. What I need to do is parse the "data" object so that I can return the "output" string from data to my web page. Any help would be greatly appreciated.
我有以下函数,它当前只显示从GET请求返回到控制台的对象。我需要做的是解析“数据”对象,以便我可以将“输出”字符串从数据返回到我的网页。任何帮助将不胜感激。
window.onload = function() {
var output = $.ajax({
url: 'https://ajith-holy-bible.p.mashape.com/GetVerseOfaChapter?Book=John&chapter=3&Verse=16', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function (data) {
//
//Change data.source to data.something , where something is whichever part of the object you want returned.
//To see the whole object you can output it to your browser console using:
console.log(data);
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "my_key_here"); // Enter here your Mashape key
}
});
}
2 个解决方案
#1
0
I'm not sure how your JSON looks like but let's say is
我不确定你的JSON是怎样的,但让我们说是
{
"foo": "some value",
"bar": "some other value"
}
then you could do:
然后你可以这样做:
success: function (data) {
console.log(data);
var dataObj = $.parseJSON(data);
$.each(dataObj, function(key, value) {
if(key == "foo") {
// do something with foo's value
console.log(value);
}
if(key == "bar") {
// do something with bar's value
console.log(value);
}
});
}
#2
0
if
dataType: 'json',
and your response looks like
你的回答看起来像
{
foo:'bar'
}
you can just access like
你可以像访问一样
success: function (data) {
console.log(data.foo)
which will output
哪个会输出
"bar"
also it is unnessecary to assign the request to the variable "output"
将请求分配给变量“output”也是不可靠的
if this does niot work for you you should json-lint your response, maybe the headers are not correct etc. ...
如果这对你不起作用你应该json-lint你的回答,也许标题不正确等......
#1
0
I'm not sure how your JSON looks like but let's say is
我不确定你的JSON是怎样的,但让我们说是
{
"foo": "some value",
"bar": "some other value"
}
then you could do:
然后你可以这样做:
success: function (data) {
console.log(data);
var dataObj = $.parseJSON(data);
$.each(dataObj, function(key, value) {
if(key == "foo") {
// do something with foo's value
console.log(value);
}
if(key == "bar") {
// do something with bar's value
console.log(value);
}
});
}
#2
0
if
dataType: 'json',
and your response looks like
你的回答看起来像
{
foo:'bar'
}
you can just access like
你可以像访问一样
success: function (data) {
console.log(data.foo)
which will output
哪个会输出
"bar"
also it is unnessecary to assign the request to the variable "output"
将请求分配给变量“output”也是不可靠的
if this does niot work for you you should json-lint your response, maybe the headers are not correct etc. ...
如果这对你不起作用你应该json-lint你的回答,也许标题不正确等......