变量未从AJAX Java脚本返回(尽管Java脚本接收到它)

时间:2014-06-02 作者:MikeiLL

我正在将变量接收到JavaScript中,但没有在PHP中获取它,我认为它在JavaScript中的编码不正确:

function glitch_player_display(mix_name) {
  alert(mix_name);
  throb.start();
  jQuery.ajax({
    type: \'POST\',
    url: ajaxglitch_playerajax.ajaxurl,
    data: {
      action: \'ajaxglitch_player_ajaxhandler\',
      mix_name: mix_name
    },
    success: function(data, textStatus, XMLHttpRequest) {
      throb.stop();
      var showglitchplayer = \'#showglitchplayer\';
      jQuery(showglitchplayer).html(\'\');
      jQuery(showglitchplayer).append(data);
    },
    error: function(MLHttpRequest, textStatus, errorThrown) {
      alert(errorThrown);
    }
  });
}
这是PHP:

add_action( \'wp_ajax_nopriv_ajaxglitch_player_ajaxhandler\', \'ajaxglitch_player_ajaxhandler\' );
add_action( \'wp_ajax_ajaxglitch_player_ajaxhandler\', \'ajaxglitch_player_ajaxhandler\' );

function ajaxglitch_player_ajaxhandler($arguments){
  var_dump($arguments);
}
返回空。

谢谢,祝你过得愉快。

1 个回复
最合适的回答,由SO网友:doublesharp 整理而成

AJAX回调不接受任何参数,您必须使用$_GET/$_POST/$_REQUEST (取决于javascript的设置方式)。这意味着mix_name 从您的POST 您将使用$_POST[\'mix_name\']. 包括add_action( \'wp_ajax_... 如果您将来还有问题的话,从代码中调用会很好,我不得不去GitHub页面查看它是如何设置的-您还缺少单引号add_action( \'wp_enqueue_scripts\', \'ajaxglitch_player_enqueuescripts\' ); 哪一个PHP可以弄清楚,但它会先将其作为常量进行尝试。配置应该是这样的:

function ajaxglitch_player_enqueuescripts() {
    wp_enqueue_script(\'ajaxglitch_player\', glitch_player_URL.\'/js/glitch_player.js\', array(\'jquery\'));
    // access ajax url on the front end as ajaxglitch_playerajax.ajaxurl
    wp_localize_script( \'ajaxglitch_player\', \'ajaxglitch_playerajax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'ajaxglitch_player_enqueuescripts\' );

// front end ajax handler
add_action( \'wp_ajax_nopriv_ajaxglitch_player_ajaxhandler\', \'ajaxglitch_player_ajaxhandler\' );
// admin ajax handler
add_action( \'wp_ajax_ajaxglitch_player_ajaxhandler\', \'ajaxglitch_player_ajaxhandler\' );

function ajaxglitch_player_ajaxhandler(){
    $mix_name = isset( $_POST[\'mix_name\'] )? $_POST[\'mix_name\'] : false;
    var_dump( "The mix_name is $mix_name" ); // this will probably break the AJAX response
    error_log( "The mix_name is $mix_name" ); // write it to the error_log too.
}

结束

相关推荐

插件选项页面中的jQuery无法正常工作吗?

我已经创建了自己的插件,它附带了一个自定义脚本。我在正确的庄园中添加了如下内容:add_action(\'admin_enqueue_scripts\', \'add_search_script\'); function add_search_script() { wp_register_script(\'search\', plugins_url(\'search.js\', __FILE__) ); wp_enqueue_script(\'search\');