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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载