Den*_*ear 5 javascript ajax html5 json node.js
使用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>
Run Code Online (Sandbox Code Playgroud)
这是我的节点服务器的一部分:用于创建服务器并侦听某些操作
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);
});
}
Run Code Online (Sandbox Code Playgroud)
没有警报被触发,所以我认为ajax不会尝试发送信息.
在服务器端尝试这个:
var port = 8000;
var http = require("http");
var server = http.createServer();
server.on('request', request);
server.listen(port);
function request(request, response) {
var store = '';
request.on('data', function(data)
{
store += data;
});
request.on('end', function()
{ console.log(store);
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.end(store)
});
}
Run Code Online (Sandbox Code Playgroud)
这在客户端:
$.ajax
({
type: "POST",
url: "http://localhost:8000",
crossDomain:true,
dataType: "json",
data:JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}})
}).done(function ( data ) {
alert("ajax callback response:"+JSON.stringify(data));
})
Run Code Online (Sandbox Code Playgroud)
希望这对你有用
| 归档时间: |
|
| 查看次数: |
20564 次 |
| 最近记录: |