gpt4 book ai didi

jquery - wordpress ajax 调用上传文件

转载 作者:行者123 更新时间:2023-12-01 01:00:39 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com