ajaxurl自定义功能的用法

时间:2018-10-23 04:18:14

标签: php ajax wordpress custom-wordpress-pages

我正在我的一个wordpress帖子中创建一个自定义表单,并使用AJAX post方法提交它。这是我的代码:

按钮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,我在开头部分的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).

我该如何解决?

1 个答案:

答案 0 :(得分:0)

在活动主题的function.php中使用以下代码

add_filter( 'allowed_http_origins', 'add_allowed_origins' );
function add_allowed_origins( $origins ) 
{
    $origins[] = 'https://yoursite.com';
    return $origins;
}

现在从https://yoursite.com到您站点的ajax url的ajax调用将在响应中具有相应的Access-Control-Allow-Origin标头。请使用以下代码

$.ajax({
    url: 'https://site1.example.com/wp-admin/admin-ajax.php',
    type: "POST",
    data: {
        ...
    },
    success: function(doc) {
        ...
    }
});