【问题标题】:Json returning null JavaScriptJson 返回 null JavaScript
【发布时间】:2018-06-26 10:51:16
【问题描述】:

我正在尝试读取一些 YouTube json 数据,但由于某种原因它在控制台中返回 null。

我正在尝试从此链接检索信息: https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=2MpUj-Aua48&format=json

前端代码:

var title;
var videoId;
var jsonObj;

ytVideoTitle(title, videoId).then(function(result) { jsonObj = 
JSON.parse(result); console.log(jsonObj); });

【问题讨论】:

    标签: javascript json


    【解决方案1】:

    这是因为title没有嵌套在html下。试试

    .then(json => console.log(json.html))
    

    .then(json => console.log(json.title))
    

    【讨论】:

    • 结果相同,为空。还有什么想法吗?
    • 试试console.log(json)。看看该数据是否符合您的预期。
    • 嗨,我现在可以让它显示查询中的所有数据,现在有办法让我只显示标题字段吗?
    【解决方案2】:

    如果你这样调用你的代码:

    var title; 
    var videoId; 
    ytVideoTitle(title, videoId).then(function(result) { console.log(result); });
    

    你的后端代码应该是这样的:

    import {fetch} from 'wix-fetch';
    
    export function ytVideoTitle(title, videoId) {
    
      return fetch("https://www.youtube.com/oembed?url=http://www.youtube.com/watch? v=2MpUj-Aua48&format=json", {method: "get"})
        .then( (httpResponse) => {
          if (httpResponse.ok) {
            return httpResponse.json();
          } else {
            return Promise.reject("Fetch did not succeed");
          }
        } ).catch(err => console.log(err));
     }
    

    因为你最后一个 .then(json => console.log(json.html["title"])) 没有返回 json 对象,所以你不会得到它作为你的 ytVideoTitle 函数的返回。

    【讨论】:

    • 以前试过这个,它仍然说'null'。还有其他想法吗?
    • 通过以下方式发布您在控制台中获得的内容:console.log(json)
    • 呃,请求似乎失败了。尝试将console.log 放入 else 块或查看控制台中的网络选项卡。您是否在网络标签中获得 200 状态?
    • 您在发出请求的 URL 中有一个空格。您是否在正在测试的代码中删除了它?如果我不这样做,我会得到 404。
    • 是的,我删除了空间。仍然没有工作,仍然是空的。
    【解决方案3】:

    试试这个

     `fetch("https://www.youtube.com/oembed?url=http://www.youtube.com/watch? v=2MpUj-Aua48&format=json", {method: "get"})
          .then( (httpResponse) => {
            if (httpResponse) {
              return httpResponse.json();
            } else {
              return console.log("Fetch did not succeed");
            }
          } )
          .catch(error => console.log(error));`
    

    【讨论】:

    • 您好,感谢您的回复。不幸的是,这给了我相同的结果,在控制台中说 null 。还有其他想法吗?为了澄清这一点,您正在查看的文件位于后端,我在前端使用以下代码调用它:var title; var videoId; ytVideoTitle(title, videoId).then(function(result) { console.log(result);
    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2017-07-20
    • 1970-01-01
    • 2011-04-28
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多