【发布时间】:2014-07-10 04:18:59
【问题描述】:
使用 Ajax,我试图将 Json 数据发送到节点服务器,不涉及任何处理,只是在发送时发出警报并在收到时发出警报:
这是我的html5:带有onclick功能的简单按钮来触发使用ajax调用的功能
<!DOCTYPE HTML>
<html>
<head>
<script>
function send()
{
//alert("Hello World");
$.ajax
({
type: "post",
url: "http://localhost:8000",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}})
}).done(function ( data ) {alert("ajax callback response:" + data);
});
</script>
</head>
<body>
<button onclick="send()">Click Me!</button>
</body>
</html>
这是我的节点服务器的一部分:用于创建服务器并监听某些操作
var port = 8000;
var server = http.createServer();
server.on('request', request);
server.listen(port);
function request(request, response)
{
var store = '';
response.writeHead(200, {"Content-Type": "text/json"});
request.on('data', function(data)
{
store += data;
});
request.on('end', function()
{
store = JSON.parse(store);
console.log(store);
response.end(store);
});
}
没有警报被触发,所以我认为 ajax 没有尝试发送信息。
【问题讨论】:
-
打开你的控制台,你有没有看到任何错误?
-
打开你的开发者工具Net标签,你看到你期望的请求和期望的响应了吗?
-
当你有一个 text/plain 内容类型时,你为什么要告诉 jQuery 期待 JSON?为什么要发送没有响应正文的 200 响应?
-
@Quentin 好的,我明白我做错了!现在它声明我的发送未被引用
-
将您的 JS 粘贴到 jshint.com 中(但我希望在加载文档时该错误会显示在 JS 控制台中)。
标签: javascript ajax json html node.js