我如何使用javascript从jSON中获得值

How can I get value from jSON using javascript?

本文关键字:jSON 何使用 javascript      更新时间:2023-09-26

如何解析"h"值从以下jSON使用javascript?

JSON内容:

info = { "title" : "Laura Branigan - Self Control", "image" : "http://i.ytimg.com/vi/p8-pP4VboBk/default.jpg", "length" : "5", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "http://ping.aclst.com/ping.php/2452159/p8-pP4VboBk?h=761944", "h" : "83135b0b3cf927b5e6caf1cf991b66b3" };

你可以试试这个。我认为这样更简单。

info.h

哦!现在我明白你的问题了。您不知道如何从url获取响应到javascript变量。为此需要一个小ajax脚本:

var youTubeUrl = "http://www.youtube-mp3.org/a/itemInfo/?video_id=p8-pP4VboBk";
var request = makeHttpObject();
request.open("GET", youTubeUrl, true);
request.send(null);
request.onreadystatechange = function() {
  if (request.readyState == 4){
    eval(request.responseText);//this should create the info variable.
    alert(info.h); //<<<---this should be it!
    //TODO: add your code to handle the info.h here.
    }
};
function makeHttpObject() {
  try {return new XMLHttpRequest();}
  catch (error) {}
  try {return new ActiveXObject("Msxml2.XMLHTTP");}
  catch (error) {}
  try {return new ActiveXObject("Microsoft.XMLHTTP");}
  catch (error) {}
  throw new Error("Could not create HTTP request object.");
}

代码主要复制自:https://stackoverflow.com/a/6375580/1311434

注意,我还没有测试这段代码,但我希望它能让你在正确的方向。请确保您可以信任从原始URL检索的代码,因为从另一个站点检索的eval()代码有点危险。

上面的字符串是一个完整的JavaScript对象,你可以把它想象成一个哈希表或一个关联键数组其中"key":"value"如果你想索引到这个数组或对象你只需使用key因此Object['key']其中key可以是int或字符串或任何对象

Json对象在javascript中完美集成。

这意味着对于定义:

var myObject = { "name": "Doe", "parents": {"father": "Louis", "mother": "Ophelia"}};

您可以简单地使用以下语句访问数据:

var myName = myObject.name;
var myFather = myObject.parents.father;
var myMother = myObject.parents.mother;

就是这么简单。

作为你问题的确切答案,它确实是info.h

更新:如果您指的是info.pf url中的h,则应该是

var h = info.pf.substr(info.pf.indexOf("?h=")+3, 999);