【问题标题】:Ajax not returning anything on form submitAjax 在提交表单时没有返回任何内容
【发布时间】:2015-04-20 12:45:54
【问题描述】:

我正在使用 wordpress 并按下提交按钮时,我希望函数通过 ajax 返回结果,结果应在屏幕上显示为警报。但是当我按下提交时,什么都没有显示。

下面是我的代码

Ajax 代码(ajaxinsert.js 文件)

jQuery(document).ready(function(){

////////////////////////////////////////////////////////////
    jQuery("#addimage").submit(function (e) { //form is intercepted
        e.preventDefault();
        //serialize the form which contains secretcode
        var sentdataa = $(this).serializeArray();

        //Add the additional param to the data        
        sentdataa.push({
            name: 'action',
            value: 'wp_up'
        })

        //set sentdata as the data to be sent
        jQuery.post(yess.ajaxurl, sentdataa, function (rez) { //start of funciton
            alert(rez);

            return false;
        } //end of function
        ,
        'html'); //set the dataType as json, so you will get the parsed data in the callback
    }); // submit end here
});

HTML 表单

<form id="addimage" action="" method="post" enctype="multipart/form-data">
<input type="submit" name="upload" style="margin-bottom:15px;">
</form>

PHP 代码(我在页面上为此代码使用了简码,下面的代码在 functions.php 文件中) add_shortcode('test', 'addimage');

function wp_up()
{   
echo "zeeshanaslamdurrani";
exit();

}

function addimage(){  

add_action( 'wp_ajax_wp_up', 'wp_up' );
add_action( 'wp_ajax_nopriv_wp_up', 'wp_up');


// register & enqueue a javascript file called globals.js
wp_register_script( 'globalss', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) ); 
wp_enqueue_script( 'globalss' );

// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'globalss', 'yess', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
} 

【问题讨论】:

  • 如果您在检查元素中打开网络窗格并提交表单,您是否收到任何消息和/或错误?
  • 控制台中没有错误,我正在使用一个名为 Dynamix 的主题...您是否认为其他内容与 ajax 代码冲突...如果您显示警报,则在文档准备就绪时显示警报但是通过ajax从函数返回的值没有显示。

标签: php jquery ajax wordpress


【解决方案1】:

将下面提到的钩子放在add_image()function 之外后试一试:

add_action( 'wp_ajax_wp_up', 'wp_up' );
add_action( 'wp_ajax_nopriv_wp_up', 'wp_up');

【讨论】:

  • 不,谢谢 Jenis ...页面仍然刷新,好像 ajax 正在工作,但是当我按下提交按钮时,alert(rez) 没有显示它应该显示。
  • 请确保您在yess.ajaxurl 中获得了价值。
  • 我怎样才能检查...请任何建议
  • jquery.post之前尝试alert(yess.ajaxurl)
  • 不显示任何警报消息...这意味着没有返回任何内容
猜你喜欢
  • 2022-01-22
  • 2020-01-27
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
相关资源
最近更新 更多