【发布时间】:2023-04-03 01:00:01
【问题描述】:
我正在尝试在 wordpress 中使用 ajax 上传文件。
我正在尝试以下形式:
<form class="form-horizontal" id="file_form">
<?php wp_nonce_field("ajax_file_nonce","security");
wp_localize_script( 'custom-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
?>
<input type="hidden" name="action" value="my_file_upload">
<input id="resume" name="resume" class="input-file form-control" type="file">
这是我的功能:
add_action('wp_ajax_my_file_upload', 'my_file_upload');
add_action('wp_ajax_nopriv_my_file_upload', 'my_file_upload');
function handle_file_upload()
{
$response['message'] = 'Done!';
echo json_encode($response); die();
check_ajax_referer('ajax_file_nonce', 'security');
if(!(is_array($_POST) && is_array($_FILES) && defined('DOING_AJAX') && DOING_AJAX)){
return;
}
if(!function_exists('wp_handle_upload')){
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$upload_overrides = array('test_form' => false);
$response = array();
foreach($_FILES as $file){
$file_info = wp_handle_upload($file, $upload_overrides);
// do something with the file info...
$response['message'] = 'Done!';
}
echo json_encode($response);
die();
}
这是我的 jquery:
jQuery(document).on(\'click\', \'#send\', function(e){
//alert();
e.preventDefault();
var ajax_url = "'.admin_url('admin-ajax.php').'"
var form_data = {};
$("#file_form").find(\'input\').each(function(){
form_data[this.name] = $(this).val();
//alert(this.name);
});
jQuery.ajax({
type: 'POST',
url: MyAjax.ajaxurl, //
data: form_data,
contentType: 'json',
success: function(response){
alert(response.message);
}
});
});
但这表明未定义 MyAjax。当我尝试在同一个 jquery 中定义的“ajax_url”变量时,它返回“未定义”消息。
这段代码有什么问题?需要进行哪些修改。请帮帮我。
【问题讨论】:
-
我试图找到所有的例子,也尝试了一切。他们建议。但不知道我错过了什么。
-
我没有成功,但我找到了这个插件并为我的使用进行了定制。 wordpress.org/plugins/alchemist-ajax-upload 感谢开发者..