【发布时间】:2020-08-17 13:50:37
【问题描述】:
我希望用户能够使用我的自定义编辑器块中的 ajax 上传 html 文件。 Wordpress 要求所有 ajax 都经过 admin-ajax.php。我的 js 代码在 Wordpress 中注册和排队的外部文件中。这是来自https://codex.wordpress.org/AJAX_in_Plugins 的Wordpress Codex 指令:
单独的 JavaScript 文件
与上一个示例相同,除了 JavaScript 位于一个单独的外部文件中,我们将调用 js/my_query.js。这些示例与插件文件夹相关。
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
对于外部 JavaScript 文件,我们必须首先 wp_enqueue_script() 以便将它们包含在页面中。此外,我们必须使用 wp_localize_script() 将值传递给 JavaScript 对象属性,因为 PHP 不能直接将值回显到我们的 JavaScript 文件中。处理函数与上例相同。
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
这是我的 PHP:
if (isset ( $_POST["test"] ) ){
echo 'test working';
}
if ( isset ( $_FILES["renee_wip_upload"] ) ){
echo 'test2';
}
这是我的js函数:
function fileSubmit(e) {
e.preventDefault();
if(typeof(files2) !== "undefined"){
//ajax using post() works fine which means the php side is OK
renee_wip_ajax_object.braft_wip_upload_value = 'test';
var data2 = {
'action': 'renee_wip_block_ajax',
'test': renee_wip_ajax_object.braft_wip_upload_value
};
jQuery.post(renee_wip_ajax_object.ajax_url, data2, function(response) {
console.log('response test: ', response);
}).fail(function(response) {
console.log('Error: ' + response.responseText);
});
//It seems $_FILES never gets populated
data = new FormData();
data.append('action', 'renee_wip_block_ajax');
for (var i = 0; i < files2.length; i++) {
var file = files2[i];
data.append('renee_wip_upload[]', file, file.name);
}
jQuery.ajax({
success: function(data){
console.log('data: ', data);
},
error: function(err){
throw err;
},
type: "post",
url: renee_wip_ajax_object.ajax_url,
data: data,
dataType: "html",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
}).done(function(msg){
console.log('done: ', msg);
}).fail(function(err){
throw err;
});
}
}
【问题讨论】: