2017-02-21 91 views
0

HI我想用html ajax調用MongoDB的,結果填充到我的HTMLHTML Ajax調用節點的MongoDB失敗

客戶端HTML(dbajax.html):

$.ajax({ 
    url: 'http://xx.xx.xx.xx:9000/db', 
    type: 'get', 
    dataType: 'jsonp', 
    jsonp: 'jsonp', // mongod is expecting the parameter name to be called "jsonp"}) 

服務器 dbserver.js

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); 

I型http://xx.xx.xx.xx:9000/dbcall它調用dbajax.html但沒有進一步發生。
我假設html ajax會調用http://xx.xx.xx.xx:9000/db並返回JSON結果。

那又怎麼了?我不想使用Express和其他框架。 謝謝

回答

0

缺失響應可能有多種原因。您不處理db.collection('Persons', ...)的錯誤情況。你應該檢查這裏是否填寫err。我建議在不同的地方添加一些console.log()聲明來看看你有多遠。

編輯:我混淆了你打電話的網址,但上面的提示仍然有效。但是,您還應該處理可能的err條件。

您還可以將一些日誌語句添加到您的dbajax.html中,以觀察瀏覽器開發者控制檯中的進度(您可以通過按F12打開它)。

+0

你好,好,但你認爲我的代碼的邏輯是正確的嗎?我在node.js中很新,所以我不確定這是否正確。 – user1042911

+0

通常你的邏輯是確定的。我想你只是給了你的申請摘錄。 「提交郵件」一些部分不需要。如果你真的不想使用快速和其他有用的框架,那麼這就是要走的路。 – Marc

+0

我將數據類型更改爲「文本」,並且它突然生效。怎麼來的? 類型:'get', dataType:'text', jsonp:'text', – user1042911