繁体   English   中英

使用 AJAX 从 node.js 接收 json 内容到 html

[英]receive json content from node.js into html using AJAX

I have this functionality where I want to send an AJAX request to the server and receive output of MySQL query on http://localhost:3000/result.html page. 这发生在单击按钮时。

<body>

<form action="/setLocation" method="POST">
  ...
<button id="get">Do Action</button>

</form>

<script>

   document.getElementById('get').onclick = function(){

   calculateAndDisplayRoute(directionsService, directionsDisplay);

   $.ajax({

    url: 'https://localhost:3000/setLocation',

    type:'POST',

    success : function(data){

    var json = JSON.parse(data);

    console.log('data received ',data); 

    val = document.getElementById('driver_details').innerHTML;

   }

 }); 

}

</script>

</body>

在我的 server.js 中,我通过以下方式处理这个问题:

const express = require("express");

var app = express();

const mySqlConnection = require("./connection");


app.post('/setLocation', function(req, res){

  r_value = between(0,7)

  value = '';

  console.log(req.body);

  mySqlConnection.query("SELECT first_name from tableX where id = ?",r_value,function  (err,result) {

    if (err) throw err;

    res.send(JSON.stringify(result));

  });

});

I am getting the json response but on http://localhost:3000/setLocation page and not on my http://localhost:3000/result.html page. 如何在发送请求的同一页面上接收响应?

这是来自 HTML 的“技巧”... <form>中的任何按钮都将充当提交按钮(没有type="submit"属性的事件)。 您需要在单击处理程序中添加一个event.preventDefault() 换句话说,改变

document.getElementById('get').onclick = function(){

经过

document.getElementById('get').onclick = function(event){
    event.preventDefault();
    // code continue here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM