find()
MongoDBメソッドから生成されたすべての結果を、 div
jQuery のメソッド経由で出力したいと考えていますgetJSON()
。
書類
{
"_id": ObjectId("34576347347"),
"content": "here is some content",
"field2": {
"subfield1": {
"0": "sf1v0",
"1": "sf1v1",
"2": "sf1v2"
},
"subfield2": "value 2"
},
"field2": "value 3"
}
PHP
<?php
$dbhost = 'username:password@127.x.xx.x:27017/';
$dbname = 'my_database';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
// specify the collection
$collection = $db->myCollection;
// define the query
$query = $collection->find(array("field2.subfield2" => "value 2"));
foreach($query as $result) {
echo $result['field2'] . " - " . $result['content'] . "<br>";
}
?>
PHP ファイルに直接アクセスすると、次のように表示されます。
value 3 - here is some content // values from the first document
value 3 - here is some content // values from the second document
以下は、div
jQueryのgetJSON()
メソッドを介して同じ出力を取得しようとする私の試みです。
jQuery
$.getJSON("http://path/to/file.php", {cid: href, format: 'json'}, function(results){
$("#my_div").html(results);
});
私が試したその他のこと
関数の使用iterator_to_array()
:
PHP
// define the query
$query = $collection->find(array("field2.subfield2" => "value 2"));
echo json_encode(iterator_to_array($query, false));
結果
div のコンテンツが空の div に変更されます。
<div id="my_div"></div>
次の結果が得られます。
PHP
// define the query
$query = $collection->find(array("field2.subfield2" => "value 2"));
echo json_encode(iterator_to_array($query, false));
jQuery
$("#my_div").html(results[0].field2 + " - " + results[0].content + "<br>" + results[1].field2 + " - " + results[1].content);
しかし、これはスケーラブルで柔軟なソリューションではありません。
次のようにjQuery.each()
と.append()
メソッドを使用する必要があると考えています。
- 配列内の各ドキュメントに対して
- その内容を div に追加します
しかし、私はまだそれを行う方法を理解できません。これは私が試したことです:
$.getJSON("http://path/to/file.php", {cid: href, format: 'json'}, function(results){
$("#my_div").html("");
$.each(results, function(){
$("#my_div").append(results.field2 + " - " + results.content + "<br>");
});
});
出力しています:
undefined - undefined
undefined - undefined