如何保持自动运行index.php的php部分? [英] how to keep running php part of index.php automatically?

查看:110
本文介绍了如何保持自动运行index.php的php部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个index.php,该文件的顶部包含php,然后是html,最后是javascript.在我的javascript部分中,我从php部分获得了值,如下所示:

I have an index.php that file contains php on top, then html and finally javascript. In my javascript part I get the values from my php part as follow:

var lati = <?php echo $valLat; ?>; var longi = <?php echo $valLong; ?>;

var lati = <?php echo $valLat; ?>; var longi = <?php echo $valLong; ?>;

然后我使用lati和longi更新地图上的标记.

and I use the lati and longi to update a marker on a map.

我如何继续使用javascript调用代码中的php部分,以获取最新的纬度和经度,而不必更新网页?

How can I keep calling the php part of my code with javascript in order to get the most recent latitude and longitude without having to update the webpage?

这是我当前使用的php代码,但是我必须重新加载整个页面才能获得新的纬度和经度.

Here is my current php code it works but I have to reload the whole page to get the new latitude and longitude.

`

/* This part will select GPS_data database and it will get the most recent latitude and longitude values
   these values are constantly updated in the database by a python file*/

//Selects GPS_data database.
mysql_select_db("GPS_data");

$sql = mysql_query("SELECT * FROM coordinates ORDER BY time DESC LIMIT 1"); //Gets the most recent lat and long.

$latitude = 'latitude';    //Set $latitude variable the same as the most recent latitude on the table.
$longitude = 'longitude';

$rows = mysql_fetch_assoc($sql);
$valLat = $rows['latitude'];
$valLong = $rows['longitude']; ?>

推荐答案

需要对PHP文件进行较小的更改,再加上一些jQuery来检索经/纬度.

Minor changes to PHP file is required, plus some jQuery to retrieve lat/lon.

更改:

  1. 在PHP代码中添加了一个数组$data.
  2. latlon作为关联数组的元素存储到$data.
  3. 将PHP数组转换为对象usig json_encode.
  4. 最后使用echo,现在$data将在jQuery中作为对象提供.
  1. Added an array $data to PHP code.
  2. Stored lat and lon as elements of associated array to $data.
  3. Converted PHP array to object usig json_encode.
  4. Finally used echo, now $data will be available in jQuery as object.

这是修改后的PHP文件.

<? 
// fetch_latlon.php

/* This part will select GPS_data database and it will get the most recent latitude and longitude values
   these values are constantly updated in the database by a python file*/

//Selects GPS_data database.
mysql_select_db("GPS_data");

$sql = mysql_query("SELECT * FROM coordinates ORDER BY time DESC LIMIT 1"); //Gets the most recent lat and long.

$latitude = 'latitude';    //Set $latitude variable the same as the most recent latitude on the table.
$longitude = 'longitude';

$rows = mysql_fetch_assoc($sql);
$valLat = $rows['latitude'];
$valLong = $rows['longitude']; 

// I have added this
$data = [
    'lat' => $valLat,
    'lon' => $valLong
];

echo json_encode($data);

?>

然后在您的HTML中添加AJAX代码.

Then in your HTML add AJAX code.

<script>

function updateLatLon() {

    $.ajax({
        // name of file to call
        url: 'fetch_latlon.php',

        // method used to call server-side code, this could be GET or POST
        type: 'GET'

        // Optional - parameters to pass to server-side code
        data: {
            key1: 'value1',
            key2: 'value2',
            key3: 'value3'
        },

       // return type of response from server-side code
       dataType: "json"

        // executes when AJAX call succeeds
        success: function(data) {
            // fetch lat/lon
            var lat = data.lat;
            var lon = data.lon;

            // show lat/lon in HTML
            $('#lat').text(lat);
            $('#lon').text(lon);
        },

        // executes when AJAX call fails
        error: function() {
            // TODO: do error handling here
            console.log('An error has occurred while fetching lat/lon.');
        }
    });

}

// fetch lat/lon after each 3000 milliseconds
setTimeout(updateLatLon, 3000);

</script>

附带说明:因为不推荐使用MySQL,所以将您的MySQL代码转换为MySQLi.

Side note: Convert your MySQL code to MySQLi because MySQL is deprecated.

有关此转换的帮助,请访问 https://www.phpclasses.org/blog/package/9199/post/3-Smoothly-Migrate-your-PHP-Code-using -the-Old-MySQL-extension-to-MySQLi.html#convert

For help in this conversion visit https://www.phpclasses.org/blog/package/9199/post/3-Smoothly-Migrate-your-PHP-Code-using-the-Old-MySQL-extension-to-MySQLi.html#convert

更新

已解决 Uncaught ReferenceError: $ is not defined

首先,您需要确保jQuery脚本已加载.这可能来自CDN或您网站上的本地.如果您在尝试使用jQuery之前不首先加载它,它将告诉您jQuery未定义.

First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.

<script src="jquery.min.js"></script>

这可以在页面的HEAD或页脚中,只需确保在尝试调用任何其他jQuery东西之前加载它即可.

This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.

然后您需要使用以下两种解决方案之一

Then you need to use one of the two solutions below

(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code, 
// or outside the document ready, enter code here
 })(jQuery); 

jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});

请注意,下面的代码很多时候都行不通,尤其是在WordPress的情况下.

Please be aware that many times following code will not work, especially true in case of WordPress.

$(document).ready(function(){
    //code here
});

这篇关于如何保持自动运行index.php的php部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆