2017-02-21 1 views
0

を失敗しましたHTML、AJAX呼び出しノードMongoDBはHI私はMongoDBのを呼び出して、私のhtml</p> <p>クライアントHTML(dbajax.html)に結果を取り込むHTML、AJAXを使用したい

http.createServer(function (request,response) 
{ 
    // serve site 
    if (request.url === "/") 
    { 
     response.writeHeader(200, {"Content-Type": "text/html"}); 
     response.write(html); 
    } 
    if (request.url === "/db") 
    { 
     console.log("db"); 
     MongoClient.connect("mongodb://localhost:27017/MyDb2", function (err, db) { 

     db.collection('Persons', function (err, collection) { 

    collection.find().toArray(function(err, items) { 
     if(err) throw err;  
     console.log(items);  
     response.writeHead(200, {"Content-Type:": "application/json"}); 
     var submittedPost = {}; 
     submittedPost['message'] = 'Proof that Node and Mongo are   working..'; 
     response.write("_wrapper('"); 
     response.write(JSON.stringify(items)); 
     response.write("')");    
     response.end(); 
    }); 

}); 

}); 
    } 
     if (request.url === "/dbcall"){ 
      console.log("dbcall"); 
      fs.readFile('./dbajax.html', function (err, html) 
     { 
     //response.writeHeader(200, {"Content-Type": "text/html"}); 
     response.write(html); 
     response.end(); 
    } 
       ) 


    } 
    //response.end(); 
}).listen(9000); 

私はそれがdbajax.html何もがさらに起こる呼び出すhttp://xx.xx.xx.xx:9000/dbcallを入力します。
html ajaxがhttp://xx.xx.xx.xx:9000/dbを呼び出し、JSON結果を返すと仮定します。

何が問題なのですか?私は、Expressや他のフレームワークを使用したくありません。 ありがとう

答えて

0

不足している応答には複数の理由が考えられます。 db.collection('Persons', ...)というエラー条件は処理されません。 errがここに入力されているかどうかを確認する必要があります。そして、私はあなたがどれだけ遠くにいるかを見るために、異なる点でいくつかのconsole.log()文を追加することを提案します。

EDIT:あなたが呼び出しているURLが混ざっていますが、上記のヒントはまだ有効です。ただし、可能なerrの条件をfs.readFile(...)にも処理する必要があります。

dbajax.htmlにいくつかのログステートメントを追加して、ブラウザのデベロッパーコンソールで進行状況を見ることもできます(F12キーを押すと開くことができます)。

+0

こんにちは、OKですが、私のコードのロジックは正しいと思いますか?私はnode.jsでかなり新しいので、正しい方法であるかどうかはわかりません。 – user1042911

+0

一般的にあなたのロジックはOKです。私はあなたのアプリケーションの抜粋だけを与えたと思います。 'submittedPost'のような部分は不要です。あなたが本当に急行や他の有用なフレームワークを使用したくないのなら、これはやり方です。 – Marc

+0

データ型を 'text'に変更すると、突然動作します。どうして? タイプ: 'get'、 dataType: 'text'、 jsonp: 'text'、 – user1042911

関連する問題