2013-10-05 84 views
0

我已經使用JSONP從另一個源獲取數據,該數據返回一個單詞列表以隨機取出其中一個用於遊戲中的單詞......我的源代碼看臺是;隨機從JSON字符串中選擇一個單詞

function processResult(obj) {    
    console.log(obj); 
    var blah = JSON.stringify(obj); 
    console.log(blah); 
} 

var jsonp = document.createElement('script'); 
jsonp.src = 'http://testhangmangame.net76.net?jsonp=processResult'; 
document.body.appendChild(jsonp); 

我想知道,如果以及如何從字符串中提取一個字先謝謝了!


JSON的實施例返回:

{ 
    "words": [ 
     "Finitely", 
     "Misleading", 
     "Dinning", 
     "Energizing", 
     "Untruest", 
     "Menorah", 
     "Ghoulish", 
     "Realism", 
     "Caliphate", 
     "Buttercup", 
     "Oratorio", 
     "Prefix", 
     "Gaming", 
     "Preshrunk", 
     "Harmed", 
     "Loop", 
     "Banknote", 
     "Doily", 
     "Rest of words removed" 
    ] 
} 

此JSON被包裹在processResult(...);

+0

你的控制檯輸出是什麼樣的? – ctcherry

+0

可能的重複[如何從數組中返回一個隨機值?](http://stackoverflow.com/questions/3419928/how-can-i-return-a-random-value-from-an-array) – Barmar

+0

請發佈服務器響應示例。我相信你的問題與JSON無關(JSONP實際上與JSON沒有任何關係)。 –

回答

4

JSONP負責將結果轉換爲普通的Javascript對象,所以JSON是無關緊要的。你只需要將數組從對象中取出,並使用標準方式來選擇一個隨機元素。

function processResult(obj) {    
    var words = obj.words; 
    var random_word = words[Math.floor(Math.random() * words.length)]; 
    console.log("The word is: "+random_word); 
} 
+0

哦,非常感謝你!我會盡快接受你的回答。感謝您提供有關JSONP的信息 –

0

如果API的精心打造和JSON響應外地返回數組:如果將JSON返回一個字符串,你將不得不作出一個數組第一

var arr = json['array_field']; 
var random = arr[Math.floor(Math.random() * arr.length)]; 

var arr = json['string_field'].split(/\W{1,}/); // Split by whitespace 
var random = arr[Math.floor(Math.random() * arr.length)]; 
相關問題