我正在尝试在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“变量时,它返回"undefined”消息。
这段代码有什么问题?需要做哪些修改。请帮帮我。
发布于 2015-08-19 00:26:30
这可能取决于如何加载jQuery脚本以及如何使用wp_localize_script函数。
在您的functions.php文件中尝试执行以下操作:
add_action( 'wp_enqueue_scripts', function(){
wp_enqueue_script( 'custom-ajax-request', get_stylesheet_directory_uri().'/js/custom-ajax-request.js', array('jquery') );
wp_localize_script( 'custom-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
} );wp_enqueue_script函数加载jQuery脚本(我将文件命名为custom-ajax-request.js),wp_localize_script将MyAjax变量传递给脚本(确保使用相同的句柄,在本例中为'custom-ajax-request')。
此外,还应该取消jQuery脚本中的字符串的引号,并从模板文件的表单中删除wp_localize_script行。
发布于 2015-08-19 12:42:35
删除
contentType: 'json'来自jquery,并尝试一下。
我在以前的堆栈答案中的某个地方读过
https://stackoverflow.com/questions/32075148
复制相似问题