【发布时间】:2018-10-23 04:18:14
【问题描述】:
我正在我的一篇 wordpress 帖子中创建一个自定义表单,并使用 AJAX 发布方法提交它。这是我的代码:
按钮的 HTML :
<button onclick="result()" type="button" name="result_submit" id="result_submit" >Submit</button>
jquery:
function result(){
$.ajax({
url :ajaxurl,
type :'POST',
action :'expense',
success: function(data){
$("#result").html(data);
}
});
}
要使用 ajaxurl,我在 head 部分的 php 代码下面添加了:
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
然后将以下代码添加到我的functions.php文件中:
add_action( 'wp_ajax_expense', 'expense_check' );
add_action( 'wp_ajax_nopriv_expense', 'expense_check' );
function expense_check(){
include_once 'dbConnection.php';
$stmt = mysqli_stmt_init($conn);
$income = "select SUM(amount) as incomeNumber FROM wp_formdata WHERE entry_type='Income'";
$response = '';
if (! mysqli_stmt_prepare($stmt,$income)) {
$response = '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$income_sum = mysqli_fetch_assoc($result);
$response = "Total Income is ".$income_sum['incomeNumber'];
}
echo $response;
}
但它不起作用。我在控制台中遇到以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost/wordpress/wp-admin/admin-ajax.php. (Reason: CORS request did not succeed).
我该如何解决这个问题?
【问题讨论】:
-
您尝试从哪个页面发起调用?
标签: php ajax wordpress custom-wordpress-pages