当一个文件上传到我的页面时,我会调用ajax在数据库中添加一个条目。然后,我想使用wp\\u localize\\u script将一个字符串发送回客户端,但当我尝试访问它时,只会收到一个错误:“未捕获引用错误:pw\\u script\\u vars未定义”。
我知道我可以用wp\\u die发回一些东西,但这是一个小问题,我认为这不是正确的方法。所以问题是为什么wp\\u localize\\u脚本不起作用?感谢您的帮助。
剧本js公司:
var ajaxurl = "<?php echo admin_url(\'admin-ajax.php\'); ?>";
jQuery(function($) {
var i;
for(i=1;i<21;i++){
$(\'body\').on(\'change\', \'#file\'+i, function() {
var file_data = $(this).prop(\'files\')[0];
var id = $(this).attr(\'id\');
var form_data = new FormData();
form_data.append(\'file\', file_data);
form_data.append(\'action\', \'file_upload\');
jQuery.ajax({
url: ajaxurl,
type: \'POST\',
contentType: false,
processData: false,
data: form_data,
success: function (response) {
alert( pw_script_vars.alert );
}
});
});
}
});
功能。php:
add_action(\'wp_enqueue_scripts\',\'owr_scripts_function\');
add_action( \'wp_ajax_file_upload\', \'file_upload_callback\' );
add_action( \'wp_ajax_nopriv_file_upload\', \'file_upload_callback\' );
function owr_scripts_function() {
wp_enqueue_script( \'script\', get_stylesheet_directory_uri() . \'/script.js\', array(\'jquery\'), time(), false);
}
function file_upload_callback(){
wp_localize_script(\'script\', \'pw_script_vars\', array(
\'alert\' => __(\'Hey! You have clicked the button!\', \'pippin\'),
\'message\' => __(\'You have clicked the other button. Good job!\', \'pippin\')
)
);
wp_die("upload success");
}
`
最合适的回答,由SO网友:Milan Hirpara 整理而成
请尝试以下代码:
剧本js公司
jQuery(function($) {
var i;
for(i=1;i<21;i++){
$(\'body\').on(\'change\', \'#file\'+i, function() {
var file_data = $(this).prop(\'files\')[0];
var id = $(this).attr(\'id\');
var form_data = new FormData();
form_data.append(\'file\', file_data);
form_data.append(\'action\', \'file_upload\');
jQuery.ajax({
url: pw_script_vars.ajax_url,
type: \'POST\',
contentType: false,
processData: false,
data: form_data,
success: function (response) {
alert( response.alert );
}
});
});
}
});
功能。php
add_action(\'wp_enqueue_scripts\',\'owr_scripts_function\', 20);
function owr_scripts_function() {
wp_enqueue_script( \'script\', get_stylesheet_directory_uri() . \'/script.js\', array(\'jquery\'), time(), false);
wp_localize_script(
\'script\',
\'pw_script_vars\',
array(
\'ajax_url\' => admin_url(\'admin-ajax.php\'),
)
);
}
add_action( \'wp_ajax_file_upload\', \'file_upload_callback\' );
add_action( \'wp_ajax_nopriv_file_upload\', \'file_upload_callback\' );
function file_upload_callback(){
$response = [];
$response[\'alert\'] = __(\'Hey! You have clicked the button!\', \'pippin\');
$response[\'message\'] = __(\'You have clicked the other button. Good job!\', \'pippin\');
wp_send_json($response);
wp_die("upload success");
}