【发布时间】: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从函数返回的值没有显示。