我试图在javascript中使用PHP等效。
caret::train(...)
我不知道如何在javascript中循环json响应。这就是我试过的:
<?php
$file = file_get_contents("http://cgnow.fun/DiscordMessageGetter/index.php");;
$file = json_decode($file);
foreach($file->messages as $object) {
var_dump($object->message);//Displays message
}
如何在javascript中使用PHP执行相同的循环?
答案 0 :(得分:1)
你可以在javascript中循环浏览json,如:
for(key in json){
console.log(key,json[key]);
}
答案 1 :(得分:0)
你得到循环错误的基本语法:
for (json.messages in object){
alert(object.message);
}
假设您想要在json.messages
中循环消息,并使用object
以外的名称(因为它可能是内置系统),您实际上会按如下方式编写它:
for (alertMessage in json.messages){
alert(alertMessage);
}
另见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
你基本上得到了变量和数组错误的位置:变量位于in
的左侧。
答案 2 :(得分:0)
要在JavaScript中循环使用JSON,请使用for ... in ...
循环,如下所示:
var json = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
for (key in json) {
console.log(key + ": " + json[key]);
}
&#13;