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和其他框架。 謝謝
你好,好,但你認爲我的代碼的邏輯是正確的嗎?我在node.js中很新,所以我不確定這是否正確。 – user1042911
通常你的邏輯是確定的。我想你只是給了你的申請摘錄。 「提交郵件」一些部分不需要。如果你真的不想使用快速和其他有用的框架,那麼這就是要走的路。 – Marc
我將數據類型更改爲「文本」,並且它突然生效。怎麼來的? 類型:'get', dataType:'text', jsonp:'text', – user1042911