2016-09-15 58 views
-1

這些是我的代碼塊。 API端點帶節點jQuery的jQuery ajax調用

 app.get('/clients/zvb/:id', function(req, res) { 
console.log('ZVB Query loaded as var = file;') 
var path = './public/queries/zvb.sql' 
var zvb = fs.readFileSync(path, "utf8") 
zvb = zvb.splice(25, 0, req.params.id) 
request.query(zvb, function(err, recordset) { 
    console.log(recordset); 
    res.end(JSON.stringify(recordset)); 
}); 

})

然後我的index.html,我試圖從端點獲得數據。

 $.ajax({ 
    type: 'GET', 
    url: 'http://localhost:8081/clients/zvb/16601', 
    dataType: 'jsonp', 
    success: function(data) { 
     console.log(data); 
     console.log('we got to here..') 
    } 
}); 

目前沒有太多的事情發生。當我嘗試在終端上手動運行ajax調用時,

Object {readyState: 1} 

端點正在工作,如果我查看它,我可以看到我之後的JSON。

湯姆

+0

從文檔,你應該[res.send()](http://expressjs.com/en/4x/api.html#res.send)或[res.json() ](http://expressjs.com/en/4x/api.html#res.jsonhttp://expressjs.com/en/4x/api.html#res.end)如果你想發送數據,而不是[ res.end()](http://expressjs.com/en/4x/api.html#res.jsonhttp://expressjs.com/en/4x/api.html#res.end)。在你的Ajax調用中你不應該期待'json'而不是'jsonp'? –

+0

'dataType:'jsonp','爲什麼?你知道jsonp是什麼嗎? –

+0

'readFileSync'從不在服務器上使用此方法,而不是接收http請求。改用異步版本。 –

回答

-1

如果您正在使用jQuery 1.5+這些速記方法是非常容易使用。 (我不能評論或會問)。文件是在這裏http://api.jquery.com/category/ajax/shorthand-methods/

$.get("http://localhost:8081/clients/zvb/16601", function(data) { 
    var data = JSON.parse(data); 
    }) 
    .done(function() { 

    }) 
    .fail(function() { 

    }) 
    .always(function() { 

    });