我只是想对此进行测试。
例如,这是节点JS中的服务器代码。
正如我在下面提到的,我想正确且简单地进行onclick事件。
因为它仅用于客户端测试。
如何解决?这样的错误使用方式是吗?
http.createServer((request, response) => {
return request
.on('error', (err) => {
console.error(err);
})
.on('data', (data) => {
//data exists
}).
on('end',()=>{
response.statusCode = 200;
response.writeHead(200, {'Content-Type':'text/html'});
response.write('<html>');
response.write('<h1> List</h1>');
response.write('<button onclick="sendToServer(data)">submit</button>'); <--this line
//I want to make onclick event for above
//but it excutes even user didnt click the button
response.write('</html>');
});
}).listen(3030);
function sendToServer(data){
request.post({
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': "application/json"
},
url:'https://...',
body:JSON.stringify(data)
}, function(e, r, body){
console.log(body);
});
}
答案 0 :(得分:0)
您需要在服务器端实现HTTP路由以侦听客户端请求
使请求发送到客户端服务器的功能(我已经使用了简单的jquery ajax get方法)
最后的工作代码在这里
var http = require('http');
var HttpDispatcher = require('httpdispatcher');;
var dispatcher = new HttpDispatcher();
http.createServer((request, response) => {
return request
.on('error', (err) => {
console.error(err);
})
.on('data', (data) => {
//data exists
}).
on('end',()=>{
dispatcher.dispatch(request, response);
});
}).listen(3030);
dispatcher.onGet("/", function(request, response) {
response.statusCode = 200;
response.writeHead(200, {'Content-Type':'text/html'});
response.write('<html>');
response.write('<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="crossorigin="anonymous"></script>');
response.write('<script>function sendToServer(){$.ajax("/route").done(function(data){alert( data );});}</script>');
response.write('<h1> List</h1>');
response.write('<button onclick="sendToServer()">submit</button>');
response.write('</html>');
response.end();
});
dispatcher.onGet("/route", function(request, response) {
response.end("Server responding!!!"); //call your any serverside function here
});