我从AngularJS开始,我想在我的WordPress网站上使用它。
我正在尝试使用WordPress数据库中的表数据打印一个表,但我无法访问WordPress函数和变量。
以下是我的一些代码。
页面demo.php
<?php
/*
* Template Name: Demo
*/
get_header();
?>
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script language="JavaScript"
src="<?php echo get_option('siteurl')?>/wp-content/themes/theme1200/js/app.js"></script>
<script language="JavaScript"
src="<?php echo get_option('siteurl')?>/wp-content/themes/theme1200/js/smart-table.min.js"></script>
<meta name="description"
content="Basic AngularJS example of data binding" />
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body >
<div ng-app="myApp" ng-controller="mainCtrl">
<h3>Basic Smart-Table Starter</h3>
<table st-table="rowCollection" class="table table-striped">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>birth date</th>
<th>balance</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rowCollection">
<td>{{row.NOMBRE}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
<?php
get_footer();
?>
app.js
angular.module('myApp', [ 'smart-table' ]).controller('mainCtrl',
function($scope, $http) {
$http.get('../wp-content/themes/theme1200/model/model.php').
success(function(data) {
$scope.rowCollection = data;
})
});
model.php
<?php
global $wpdb;
//$query = "SELECT * FROM JUGADOR";
//$resultado = $wpdb->get_results($query);
$sql = "SELECT APELLIDOS, NOMBRE, HANDICAP FROM JUGADOR ORDER BY APELLIDOS";
$res = $wpdb->get_results($wpdb->prepare($sql));
$result = $res->fetchAll( PDO::FETCH_ASSOC );
# JSON-encode the response
$json = json_encode( $result );
echo $json;
?>
但是在执行以下行时我遇到了错误。
$res = $wpdb->get_results($wpdb->prepare($sql));
我认为这个文件无法访问wordpress函数和变量。
有人能帮助我吗?
答案 0 :(得分:0)
最好使用wordpress内置的ajax函数。
Setting up ajax. I have used it outside of plugins. It works the same.
以下是代码的粗略版本
这会将代码添加到footer.php
。您还可以将脚本排入单独的js文件中(强烈推荐)。在任何一种情况下,您都想阅读ajaxurl
add_action( 'wp_footer', 'my_action_javascript' ); // Write our JS below here
function my_action_javascript() { ?>
<script type="text/javascript" >
angular.module('myApp', [ 'smart-table' ]).controller('mainCtrl', function($scope, $http) {
$http.get(ajaxurl).
success(function(data) {
$scope.rowCollection = data;
})
});
</script> <?php
}
然后在functions.php
添加以下内容。
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb;
$sql = "SELECT APELLIDOS, NOMBRE, HANDICAP FROM JUGADOR ORDER BY APELLIDOS";
$res = $wpdb->get_results($wpdb->prepare($sql));
$result = $res->fetchAll( PDO::FETCH_ASSOC );
# JSON-encode the response
$json = json_encode( $result );
echo $json;
}
这应该可以让你在那里大部分时间。检查链接,它应该可以帮助您调整它。