duanpo7282 2014-07-29 13:09
浏览 64
已采纳

如何让wp_ajax与jQuery $ .post一起使用

Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins

I have this in my functions.php:

add_action( 'admin_footer', 'my_action_javascript' );

function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
        'action': 'my_action',
        'whatever': 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

        echo $whatever;

    die(); // this is required to return a proper result
}

And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?

  • 写回答

1条回答 默认 最新

  • dongzhang1987 2014-07-29 14:11
    关注

    Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.

    Is this the only javascript you're including in the admin area?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
    • ¥15 q从常量变成sin函数,怎么改写python代码?
    • ¥15 图论编程问题,有可以指导的吗
    • ¥15 DEA的CCR模型画图
    • ¥15 请假各位一个关于安卓车机的问题
    • ¥15 光谱仪怎么看这样的透射谱
    • ¥15 pyqt5 如何实现输入框输入关键词,下拉框显示模糊查询返回的结果?
    • ¥20 fluent模拟,可以燃烧和相变同时模拟吗?
    • ¥50 海康摄像头,C#如何识别车牌号码和抓取JPG
    • ¥15 yolov5 pt转engine的问题