简体   繁体   中英

Send data between two pages with jQuery/AJAX

I am looking for a way to send data between two different Divs on two different pages, both are on the same domain.

This is more of a learning exercise as I am very new to jQuery and AJAX, I have been searching for a simple way of doing this but most answers or options seem to be complex and involve installing other software , etc.

I would like to have one html page listening for an event, the other html page will send an event when something happens, for example;

Page 1 - Countdown clock, every time it reaches a new hour it sends the data to Page 2

Page 2 - Listening for this data, when received it displays the data in a div

This is not exactly what I want to do in regards to the Countdown clock, it is just an example but the theory is what I need. Is it possible to set this up with just 2 flat html pages and some jQuery/AJAX code? It does not need to be secure or optimized , like I said it is just for learning.

也许您会去看一下nodejssocket.io。这是个了不起的工具,可以通过javascript进行交互。

The simplest way is, install a server ( wamp for example), and then you can communicate between your pages, by using database or files, and then use something like that:

Page 1:

<a id="sendData">Send Data to Page 2 </a>

var url = http://localhost/yoursite/writeToFile.php
$('a#sendData').click(
               $.ajax({ url: url, type: "POST", data:{test:'test'} })
                .done(function() {
                      $(this).append(' sent!');
               });
)};

Page 2:

<div>Listening to Page 1 </div>

window.setInterval(function(){
 listenToPage1();
}, 5000);

 function listenToPage1()
{
    var url = http://localhost/yoursite/readFromFile.php
    $.get(url, function(data) { $('div').html(data);   });
}

writeToFile.php

<?php
   $fp = fopen('data.txt', 'a');
   fwrite($fp, $_POST);
   fclose($fp);
?>

readFromFile.php

<?php 
   readfile('data.txt');
?>

yoursite folder:

www/
  /yousite
   readFromFile.php
   writeToFile.php
   page1.php
   page2.php
   data.txt

And of course you can use nodejs to make interactions directly by javascript , but I think it's better to start by learning the basics and then you can move to nodejs (it doesn't mean nodejs is very complicated :p)

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