【问题标题】:Call html and Php pages with Ajax使用 Ajax 调用 html 和 Php 页面
【发布时间】:2023-03-19 22:59:01
【问题描述】:

我创建了一个 ajax 函数,它在我的 index.php 中的 ajax-container div 中调用我的 html 页面,所以现在如果我还想在 ajax 中调用 php 页面,我该怎么办?

这是我的代码:

htaccess 重写

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([a-zA-Z0-9\-]*).html$ index.php?p=$1 [L]

index.php

<div class="link" href="page2.html">go html</div>
<div class="link" href="page3.php">go php</div>

<div id="ajax-container">
         <?php
$d = "pages/";

if (isset($_GET['p']))
	{
	$p = strtolower($_GET['p']);
	if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".html"))
		{
		include $d . $p . ".html";

		}
	  else
		{
		include $d . "404.html";

		}
	}
  else
	{
	include $d . "home.html";

	} ?>
</div>

这是我的 ajax 函数从文件夹 pages 调用 html 页面/

var afficher = function(data, page) {

    $('#ajax-container').fadeOut(100, function() {
        $('#ajax-container').empty();
        $('#ajax-container').append(data);
        $('#ajax-container').fadeIn(100, function() {});
    });
};

var lastRequest = null;
if (lastRequest !== null) {
    lastRequest.abort();
}

var loadPage = function(page, storeHistory) {
    if (typeof storeHistory === 'undefined') {
        storeHistory = true;
    }


    lastRequest = $.ajax({
        url: 'pages/' + page,
        cache: false,
        success: function(html) {
            afficher(html, page);
            if (storeHistory === true) {
                history.pushState({
                    'key': 'value',
                    'url': page
                }, '', page);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            afficher('erreur lors du chagement de la page');
        }
    });

    return false;
};

window.addEventListener('load', function() {
    setTimeout(function() {
        window.addEventListener('popstate', function(e) {
            if (e.state === null) {
                loadPage('home.html');
            } else {
                loadPage(e['state']['url'], false);
            }
        });
    }, 0);
});

$(document).ready(function() {
  
    $('.link').bind('click', function(e) {
     e.preventDefault();
     var page = $(this).attr('href');
     loadPage(page);
     return false;
    });
  
});

【问题讨论】:

    标签: javascript php jquery html ajax


    【解决方案1】:

    如果你想执行 php 并在 div 上显示它返回的内容,你可以使用 jQuery 和 ajax:

    $(function(){
        $(".myDivClass").load('yourPHPFile.php');
    }());
    

    【讨论】:

    • 谢谢它正在工作,但我如何将它用于我的 popstate 功能?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-03-07
    • 1970-01-01
    • 2014-01-03
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多