简体   繁体   English

使用jQuery / AJAX在两个页面之间发送数据

[英]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. 我正在寻找一种在两个不同页面上的两个不同Divs之间发送数据的方法,它们都在同一个域中。

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. 这更多的是学习练习,因为我是jQuery和AJAX的新手,我一直在寻找一种简单的方法来执行此操作,但是大多数答案或选项似乎都很复杂,并且涉及安装其他软件等。

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; 我想让一个html页面侦听一个事件,例如,当某个事情发生时,另一个html页面将发送一个事件。

Page 1 - Countdown clock, every time it reaches a new hour it sends the data to Page 2 第1页-倒数时钟,每到一个新的小时,它就会将数据发送到第2页

Page 2 - Listening for this data, when received it displays the data in a div 第2页-侦听此数据,当接收到它时,它会在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? 是否可以仅用2个平面html页面和一些jQuery / AJAX代码进行设置? 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: 最简单的方法是安装服务器(例如wamp ),然后可以使用数据库或文件在页面之间进行通信,然后使用类似的方法:

Page 1: 第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: 第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 writeToFile.php

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

readFromFile.php readFromFile.php

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

yoursite folder: yoursite文件夹:

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) 当然,您可以使用nodejs通过javascript直接进行交互,但是我认为最好先学习基础知识,然后再转向nodejs (这并不意味着nodejs非常复杂:p)

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

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