第一次尝试AJAX请求时遇到了问题。我想在Wordpress站点的按钮点击上加载一个php文件。经过研究,我得到了以下代码:
指数php文件:
<button id="ajaxbtn">Ajax</button>
<div id="ajax">Some Text</div>
ajax。php文件(我要加载的文件):<?php echo "Hello!" ?>
功能。php文件:add_action( \'wp_enqueue_scripts\', \'myajax_data\', 99 );
function myajax_data(){
wp_localize_script(\'menu_toggle\', \'myajax\',
array(
\'ajax_url\' => admin_url(\'admin-ajax.php\')
)
);
}
add_action(\'wp_ajax_tablo\', \'tablo\');
add_action(\'wp_ajax_nopriv_tablo\', \'tablo\');
function tablo() {
// Grab php file output from server
ob_start();
include(get_template_directory_uri() . \'/ajax.php\');
$result[\'content\'] = ob_get_contents();
wp_send_json($result);
}
menu\\u切换。js文件(带有ajax代码的js文件):$("#ajaxbtn").click(function () {
$.ajax({
type : \'post\',
dataType : \'json\',
url : myajax.ajax_url,
data : {action: \'tablo\'},
success: function(response) {
//load the fetched php file into the div
console.log(response);
alert(response);
$(\'#ajax\').append("hello");
$(\'#ajax\').load(response.content);
}
});
});
我真的可以alert(response);
通知[对象对象],以及$(\'#ajax\').append("hello");
显示,这意味着ajax连接正确,ajax请求工作正常。但是$(\'#ajax\').load(response.content);
在#ajax div中加载相同的整个索引页,而不是加载ajax的内容。我真正想要的php文件。我可能在function tablo()
函数的。php文件,或在ajax代码中的menu\\u切换。js文件。这个console.log(response);
输出量惊人。有人能帮我做这个吗?