我想创建一个像这样的网页.. https://www.placementpreparation.io/quantitative-aptitude/average/questions-and-answers/ 我正在使用 divi builder 在 WordPress 中创建网站。我尝试使用以下ajax代码在单击按钮时仅显示来自不同网页的网页的一部分..
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
</head>
<body>
<h2 style="color: green;">
just trial
</h2>
<h3>
fetch only sections of specific HTML areas
from an external page using AJAX
</h3>
<button onclick="event_occur()">
Click Here
</button><br><br>
<h3>External.html page</h3>
<div id="display"
style="border: 1px solid black;
width:max-content;
padding:0.5rem">
fetched Content will display here.
</div>
<script>
event_occur = () => {
// Load the Section with .first class and display
$("#display").load("index.html .first");
};
</script>
</body>
</html>
index.html页面如下...
<!DOCTYPE html>
<html lang="en">
<head>
<title>webpage from wherer content is loaded</title>
</head>
<body>
<section class="first">
<h3>
Index.html - Section - class = "first"
</h3>
<h2 style="color: green;">
content from here will be loaded
</h2>
<h3>Web Development</h3>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JAVA SCRIPT</li>
<li>JQUERY</li>
</ul>
</section>
<section class="second">
<h2 style="color: green;">
this will not load
</h2>
<h3>Machine Learning</h3>
<ul>
<li>Python</li>
</ul>
</section>
<section class="third">
<h2 style="color: green;">
this will not load
</h2>
<h3>Courses</h3>
<ul>
<li>Interview Preparation</li>
<li>DSA</li>
<li>DBMS</li>
</ul>
</section>
</body>
</html>
当我单击按钮单击此处时,代码既不会加载完整页面index.html,也不会加载使用divi主题的divi页面构建器在WordPress构建中页面index.html的所需部分 我应该怎么做才能使代码正常工作..thanx
我尝试了上述逻辑并期望网页的部分将在ajax调用上加载。
首先,请记住进行备份和/或不要在生产中进行更改。
您的代码无法按原样在 WordPress 中运行。这是原因以及解决方法:
这里有一个快速解决方法:
代码:
function enqueue_custom_script() {
wp_enqueue_script('custom-ajax', get_template_directory_uri() . '/js/custom-ajax.js', array('jquery'), null, true);
wp_localize_script('custom-ajax', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_script');
function load_question() {
$page = get_page_by_path('questions');
$content = apply_filters('the_content', $page->post_content);
$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new DOMXPath($dom);
$first_section = $xpath->query("//section[contains(@class, 'first')]")->item(0);
echo $dom->saveHTML($first_section);
wp_die();
}
add_action('wp_ajax_load_question', 'load_question');
add_action('wp_ajax_nopriv_load_question', 'load_question');
代码:
jQuery(document).ready(function($) {
$('button').on('click', function() {
$.ajax({
url: ajax_object.ajax_url,
type: 'POST',
data: {
action: 'load_question'
},
success: function(response) {
$('#display').html(response);
}
});
});
});
这应该适用于 WordPress 和 Divi。如果没有,请检查您的浏览器控制台是否有错误,然后将其发送至此处。