我正在制作一个带有子菜单的网站,它将内容渲染到div。该网站由Wordpress提供支持,网站的这一部分是我制作的插件。我希望div的内容从数据库中获取信息,即我想添加PHP代码。但是似乎不能添加任何PHP。如果我将加载的内容设为PHP文件,由于JS中的jQuery('#pageContent').html(msg),它将无法工作,如果我将PHP代码添加到一个HTML文件中,该代码似乎无法识别。有什么方法可以做到这一点呢?我也许应该补充说,我想要添加的PHP是表单的一部分,据我所知,需要与HTML位于同一文件中。
下面是使用Ajax加载内容的JS函数:
function loadPage(url) //the function that loads pages via AJAX
{
url=url.replace('#page',''); //strip the #page part of the hash and leave only the page number
jQuery('#loading').css('visibility','visible'); //show the rotating gif animation
jQuery.ajax({ //create an ajax request to load_page.php
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'ajax_request2',
page: url //with the page number as a parameter
},
dataType: "html", //expect html to be returned
error: function(xhr, textStatus, textError) {
console.log(textError);
},
success: function(msg) {
window.alert("Working loadPage ajax!");
if(parseInt(msg)!=0) //if no errors
{
jQuery('#pageContent').html(msg); //load the returned html into pageContent
jQuery('#loading').css('visibility','hidden'); //and hide the rotating gif
}
}
});
}发布于 2019-10-04 15:54:02
我稍微修改了您的函数,并将其定向到JSON数据的测试站点。这个小片段可以工作。也许这对你有帮助?
由于测试站点只返回JSON,所以我放入#pageContent的"html“并不是真正的html,但我希望您能明白这一点。
如果您想知道Ajax返回了什么,那么您总是可以在正确的位置插入一个console.log(msg) (参见下面的注释掉的行)。
为了清楚起见,如果加载的内容是由PHP脚本生成的,那么loadPage函数中的url当然应该指向相关服务器上的PHP脚本。此脚本将查找数据并将其处理为所需的html格式,然后将其作为对Ajax请求的响应发送回来。
function loadPage(url){
url=url.replace('#page',''); //strip the #page part of the hash and leave only the page number
jQuery('#IAmloading').show(); //show the rotating gif animation
jQuery.ajax({ //create an ajax request to load_page.php
type: "GET",
url: url, // the URL of the page to be loaded ...
data: {action: 'ajax_request2', id: 4}, //your further parameters ...
dataType: "json", //expect json to be returned
error: function(xhr, textStatus, textError) { console.log(textError);},
success: function(msg){ console.log("Working loadPage ajax!");
// console.log(msg); // show what the AJAX request returned
if(msg) //if no errors
{
jQuery('#pageContent').html(JSON.stringify(msg)); //put msg into pageContent
jQuery('#IAmloading').hide(); //and hide the rotating gif
}
}
});
}
// call the function with the URL of a test site (returns JSON only ...):
loadPage('https://jsonplaceholder.typicode.com/users');#IAmloading {visibility: hidden}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="IAmloading">Please wait, page is loading ...</div>
<div id="pageContent"></div>
https://stackoverflow.com/questions/58231578
复制相似问题