我正在开发一个插件,它通过ajax获取数据并将数据显示到表中。
这是我的插件代码:
<?php
/*
Plugin Name: Issue Shower
Version: 1.0
*/
add_action(\'widgets_init\', \'klissue_register\');
function klissue_register() {
register_widget(\'klissue\');
}
class klissue extends WP_Widget {
function __construct() {
$widget_ops = array(
\'classname\' => \'klissue_widget_class\',
\'description\' => \'Example\'
);
parent::__construct(\'klissue\', __( \'Issue Widget\',\'issue-plugin\'), $widget_ops);
}
function form($instance) {
echo "Come from function form";
}
function update($new_instance, $old_instance) {
return $new_instance;
}
function widget($args, $instance) {
extract($args);
echo $before_widget;
?>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function foo() {
var $jq = jQuery.noConflict();
var table = document.getElementById("issue_table");
var label = document.getElementById("table_status");
$jq.get("wp-json.php", function (response, status, xhr) {
if (status != "success") {
label.innerText = "data fetch failed";
return;
}
$jq.each(response, function (k, v) {
table.innerHTML += "<tr><td>" + v.id + "</td><td>" + v.code + "</td><td>" + v.pre + "</td><td>" + v.mid + "</td><td>" + v.post + "</td></tr>";
});
label.innerText = "new issue";
});
}
var $jq = jQuery.noConflict();
$jq(document).ready(foo);
</script>
<style>
#issue_table_div{
width: min-content;
height: 6cm;
overflow-y: scroll;
}
</style>
<div id="issue_shower">
<div id="issue_table_div">
<table id="issue_table"></table>
</div>
<label id="table_status">Test Label</label>
</div>
<?php
echo $after_widget;
}
}
这个插件在wordpress的主页上运行良好。然而,如果我访问任何帖子,我的插件都不起作用。唯一元素
table
呈现到页面,但JS代码不运行。我是否遗漏了主页和贴子页之间的任何区别?
有人能帮我吗?非常感谢!
SO网友:jepser
我认为ajax请求应该指向实际的WordPress ajax处理程序。
可以通过本地化脚本来传递变量:
$js_object = [
\'ajaxUrl\' => admin_url(\'admin-ajax.php\')
];
wp_register_script(\'my-script\', \'http://url\');
wp_localize_script(\'my-script\', \'pluginObject\', $js_object);
wp_enqueue_script(\'my-script\');
将ajax请求注册到ajax挂钩中:
function widget_ajax_request()
{
// your stuff
}
add_action(\'wp_ajax_my_action\', \'widget_ajax_request\');
add_action(\'wp_ajax_nopriv_my_action\', \'widget_ajax_request\');
你的JS应该是:
$jq.ajax({
url: pluginObject.ajaxUrl, //from the localized object
data: {
action: \'my_action\' //from the hook
},
success: function() {
// your stuff
}
})
以下是教程:
https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/