如何使用javaScript和jQuery从URL保存JSON对象

时间:2019-12-15 04:32:01

标签: javascript jquery json

所以我有一个php页面,它以正确的格式返回JSON对象。喜欢:

  [ 
    {
    "name":"Users",
    "parent":"null",
    "children":[ {
        "name": "adsd", "parent": "Users", "children": []
    }
    ,
    {
        "name": "ca", "parent": "Users", "children": []
    }
    ,
    {
        "name":"ChanakaP",
        "parent":"Users",
        "children":[ {
            "name": "Carlos Puyol rejects Barcelona sporting director role", "parent": "ChanakaP"
        }
        ,
        {
            "name": "\r\nDiego Costa could leave Atletico Madrid", "parent": "ChanakaP"
        }
        ,
        {
            "name": "FIFA insist Lionel Messi's award for best men's player was not rigged", "parent": "ChanakaP"
        }
        ,
        {
            "name": "\r\nReal madrid interested in Van De Beek", "parent": "ChanakaP"
        }
        ,
        {
            "name": "Hazard scores debut goal", "parent": "ChanakaP"
        }
        ]
    }
    ,
    {
        "name": "dsd", "parent": "Users", "children": []
    }
    ,
    {
        "name": "ggggggggggggggggg", "parent": "Users", "children": []
    }
    ,
    {
        "name":"james123",
        "parent":"Users",
        "children":[ {
            "name": "first post", "parent": "james123"
        }
        ]
    }
    ,
    {
        "name": "new", "parent": "Users", "children": []
    }
    ,
    {
        "name": "new123", "parent": "Users", "children": []
    }
    ,
    {
        "name": "test", "parent": "Users", "children": []
    }
    ]
  }
]

我需要获取此JSON对象并将其以

的形式传输到脚本中的变量中
var obj = k;

其中k是从此URL返回的JSON对象。我已经导入了jQuery并尝试了$ .getJSON方法,但没有成功。因此,如果您有一个带有JSON对象的URL“ ex.com”,我该如何将其完全保存到变量中。因此,如果我将网址的输出直接复制到类似这样的变量中:

var obj2 = copiedJSON;

我的函数按预期工作,但是当我使用$ .getJSON时:

$.getJSON('http://localhost/CS3744-N/GoalLiga/viz', function(json){
     obj2 = json;
});

我的函数返回错误。 JSON函数是否更改返回的输出。

1 个答案:

答案 0 :(得分:1)

您没有发布您尝试用于$ .getJSON的代码,所以我不能告诉您为什么它被破坏了,但是这是您将如何使用$ .getJSON来实现您的解决方案:

// You can change api.github.com to any URL you want and it should still work
$.getJSON("https://api.github.com", function(json){ 
    // This is the callback function. The variable json will only be avaliable within this function
    console.log(json); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

请注意,只有在提供给$ .getJSON的函数中才可以使用json变量,这是因为GET请求是异步执行的(例如,在发出请求时,其余代码将继续运行),因此确保将要运行的所有依赖json的代码放在回调函数中。