我的目标是在WordPress中创建最简单的ajax调用,但我不知道它是如何工作的。
JS文件:
jQuery("#votepostform").submit(function() {
var url = "file.php"; // php script to handle form
jQuery.ajax({
type: "POST",
url: url,
data: jQuery("#votepostform").serialize(), // serializes the form\'s elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
表单HTML:
<form action="" method="post" id="votepostform" />
<input type="hidden" name="postid" value="333" />
<button type="send" name="vote" class="vote_link"></button>
</form>
文件。php:
echo \'<script language=\\\'javascript\\\'>alert(\\\'It works! \\\');</script>\';
如何使此ajax代码在WordPress站点中工作?
SO网友:ifdion
您必须使用admin-ajax
处理程序来执行AJAX调用。
代替file.php
在里面var url = "file.php";
具有
yoursite.com/wp-admin/admin-ajax.php?action=simple_ajax
在插件/函数中。php文件,添加
add_action(\'wp_ajax_nopriv_simple_ajax\',\'process_simple_ajax\'); //for non logged in user
add_action(\'wp_ajax_simple_ajax\',\'process_simple_ajax\'); //for nlogged in user
function process_simple_ajax(){
$data = $_REQUEST; // retrieve your submitted data
wp_send_json($data); // return the processed data to the browser as json
}