开发者

Outputting text from an url that returns JSON

I'm more of a backend guy, this javascript stuff is a bit out of my area. I could really use a point in the right开发者_Python百科 direction :)

So I have an URL that, for example, returns this JSON:

[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}}, 
 {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}}, 
 {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}}, 
 {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}}, 
 {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]

I want to write a piece of javascript that I can embed in my HTML that will randomly choose and print one of the "fact"s from the JSON URL.


Hopefully this helps:

var a = '[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}}, {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}}, {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}}, {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}}, {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]';
alert(eval(a)[0].model);

Here's an example that uses AJAX to call out to a (local) web service:

$.ajax({
  url: "test.php",
  success: function(data){
    alert(eval(data).result);
  }
});


You can do it like this:

var questionData = JSON.parse(data);
var randomIndex = Math.floor(Math.random() * questionData.length);
var randomFact = questionData[randomIndex].fields.fact;

Then, what you want to do with the randomFact in your web page is up to you and you haven't provided any info on that for us to help with that. You could put the fact into an existing element on the page. You could create new elements on the page where you want them, etc...


Use JSON.parse to convert into an array and pick a random element. If you still can't get it to work post your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜