简体   繁体   中英

How can I use XMLHttpRequest() to constantly send data to another page in my website?

I'm working in node.js and express.js and am trying to find the FASTEST way I can deal with this problem.

One page in my website is receiving location information in latitude var lat and longitude var long , and I want to constantly be sending that information to another page on my website. My code is very incomplete but any guidance is extremely helpful. I'm currently getting the error http://localhost/driver/save_position Failed to load resource: net::ERR_CONNECTION_REFUSED and later POST http://localhost/driver/save_position net::ERR_CONNECTION_REFUSED in the browser console. My code is below.

This is code in a javascript file run on one webpage that I want to send the information to my other page so that it can constantly update.

function sendCoordinates(lat, lon){
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "http://" + window.location.hostname + "/driver/save_position", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send('lat=' + lat + '&lon=' + lon);
}

In a separate file for my routing I have

router.post('/driver/save_position',function(req, res, next){
  console.log(req)
})

I'm very much a beginner with all of these kinds of ideas so any advice, help, and solutions are extremely appreciated! Thank you for any help!

One web page does not send data directly to another web page unless it's in the same browser. So since you're saying "another page on your website", I assume you're talking about making data appear in some other page for some other user. If that's what you mean, then that just isn't a capability that browser Javascript has. Also, it's not really clear what you mean when you say "send to a web page" as that isn't really a destination.

What you can do is to send a request to a server and you can ask that server to notify some other connected user/page. If that other user/page has a live webSocket connect to the server, then server can send a message to that user/page over the webSocket.

If the other user/page does not have a live webSocket connection to the same server, then the only way it can get this information from the server is for it to request that information from the server with its own Ajax call. The server would have to store that information so when someone asks for it, it could supply the info.


If you are asking how to send data from one window in the browser to another window in the same browser, then you can use postMessage() to send data between two coooperating windows in the same browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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