使用 AJAX 根据屏幕大小交换

using AJAX to swap <div> contents based on screen size

本文关键字:交换 屏幕 AJAX 使用      更新时间:2023-09-26
内容。

我非常了解vanilla JavaScript,但我不知道jQuery语法,而且我很难使用AJAX。我已经阅读了大约 30 篇帖子,但无法使其在我的(相对简单和常见)场景中工作。

我有一个带有动态标题内容的 WordPress 网站(所以我需要在加载时获取 WordPress/PHP 变量),并且我正在尝试加载视频背景或帖子缩略图作为背景图像,具体取决于屏幕尺寸(我正在使用 JavaScript 检测)。检测脚本有效(加载/调整大小时),我有 PHP 脚本,我可以将其交换到我的页面中,从而成功获取视频或图像。但是现在,我该如何交换它们?(我不想同时加载两者并显示/隐藏,因为这会减慢纯图像用户的页面速度。

以下是我尝试过的一些事情,但无济于事:

			$.ajax({
			  type: "GET",
			  url: '/wordpress/wp-content/themes/myTheme/home-video.php',
			  success: function(data) {
			    $('#theDiv').html(data);
			  }
			});

			$.get("/wordpress/wp-content/themes/myTheme/home-video.php");
			$('#theDiv').replaceWith('<?php include "/wordpress/wp-content/themes/myTheme/home-video.php"; ?>');

			$('#theDiv').load('/wordpress/wp-content/themes/myTheme/home-video.php');

敢肯定,我只是对PHP函数与JS/AJAX函数的时间感到困惑,但我真的陷入了死胡同。如果有人能帮助我指出正确的方向,将不胜感激。

ajax 在 WordPress 中以不同的方式处理(参见 CODEX)

在标头中.php声明 ajax 变量。

<script>var ajaxURL = '<?php echo esc_js(admin_url('admin-ajax.php'));?>';</script>

在您的函数中.php

function Get_The_Header()
{
    if($_POST['whichOne'] == 'video'){
        get_template_part('home-video');
    } else {
        get_template_part('home-thumbnail');
    }
    exit();
}
add_action('wp_ajax_nopriv_Get_The_Header', 'Get_The_Header');
add_action('wp_ajax_Get_The_Header', 'Get_The_Header');

最后是你的 JS

function get_header(){
    "use strict";
    var whichOne = "thumbnail";
    if (window.innerWidth >= 768) {
        whichOne = "video";
    }
    var data = {
        action: 'Get_The_Header',
        whichOne: whichOne,
    };
    $.post(ajaxURL, data, function(result) {
        $("#theDiv").html(result);
    }); 
}
$(window).on("load", function() {
    get_header();
});
$(window).on("resize", function() {
   get_header();
});

好的,马克。这是我对你给我的方向所做的。

功能.php:

function Get_The_Header()
{
	if($_POST['whichOne']=='video'){
		get_template_part('home-video.php');
	} else {
		get_template_part('home-thumbnail.php');
	}
	exit();
}
add_action('wp_ajax_nopriv_Get_The_Header', 'Get_The_Header');
add_action('wp_ajax_Get_The_Header', 'Get_The_Header');

外部 JS 文件:

jQuery(function($) {
  "use strict";
  var whichOne = "thumbnail";
  $(window).on("load", function() {
    if (window.innerWidth >= 768) {
      var data = {
        action: 'Get_The_Header',
        whichOne: 'video',
      };
      $.post(ajaxURL, data, function(result) {
        $("#theDiv").html(result);
      });
    } else {
      whichOne = "thumbnail";
    } //end IF for screen detection
  }); //end listener function
}); //end jQuery function

如果可以的话,请让我知道我做错了什么。感谢您的帮助!