作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 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”变量时,它返回“未定义”消息。
这段代码有什么问题?需要进行哪些修改。请帮助我。
最佳答案
这可能取决于您如何加载 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
行。
关于jquery - wordpress ajax 调用上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32075148/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!