通过Ajax上传文件有点棘手,但易于管理。
在中向表单添加一些其他表单字段(nonce和ajax\\u action)suite_export_import_menu()
:
function suite_export_import_menu(){
?>
<h2>Suite Report Export/Import </h2>
<div id="export_import_form">
<p id="custom_ajax_call_process">Uploading...</p>
<p id="custom_ajax_call_result"></p>
<form action="<?php echo admin_url(\'admin-ajax.php\'); ?>" method="post" enctype="multipart/form-data" target="upload_target">
<input type="hidden" name="action" value="export_vacancy">
<input type="hidden" name="subaction" value="imp_vacancy">
<input type="file" name="file_source" id="file_source" value="" />
<input type="hidden" name="cmd" value="import" />
<input type="hidden" name="ajax_action" value="custom_ajax_call" />
<input type="hidden" name="_ajax_nonce" value="<?= wp_create_nonce(\'custom_ajax_call\')?>" />
<input type="submit" value="Import" /><br />
<!--input type="checkbox" name="trancate" value="1" /> replace suites-->
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:none;"></iframe>
</form>
</div>
<?php
}
将AJAX调用添加到
functions.php
或您的插件文件:
function custom_ajax_call() {
if(!wp_verify_nonce( $_POST[\'_ajax_nonce\'], \'custom_ajax_call\' )) {
die(-1);
}
$success = 0;
// Put your Code here
if ( true ) { //TODO: Change to condition if upload is success...
$success = 1;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.stopUpload(<?= $success ?>);
</script>
<?php
exit;
}
function custom_ajax_call_init() {
if($_REQUEST[\'ajax_action\'] === \'custom_ajax_call\') {
do_action( \'wp_ajax_custom_ajax_call\' );
}
}
if (is_admin()){
add_action(\'wp_ajax_custom_ajax_call\', \'custom_ajax_call\');
}
add_action( \'init\', \'custom_ajax_call_init\');
创建
custom_ajax_call.js
在主题或插件目录中:
var stopUpload,
startUpload;
jQuery(\'document\').ready(function($) {
stopUpload = function (success) {
if (success)
$(\'#custom_ajax_call_result\').empty().text(\'Success!\');
else
$(\'#custom_ajax_call_result\').empty().text(\'Fail!\');
$(\'#custom_ajax_call_process\').hide();
return true;
};
startUpload = function() {
$(\'#custom_ajax_call_process\').show();
$(\'#custom_ajax_call_result\').empty();
};
$(\'body\').on(\'submit\', \'#export_import_form\', function () {
startUpload();
});
});
将脚本排入
functions.php
或插件文件(注意事项):
function admin_enqueue_custom_ajax_call(){
wp_enqueue_script( \'jquery\' );
wp_enqueue_script( \'custom-ajax-call\', get_template_directory_uri().\'/path/to/custom_ajax_call.js\', array(\'jquery\')); //TODO: Change to plugin URI if needed
}