2017-02-21 58 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