正在尝试使用admin-ajax.php
从前端表单上载图像。我一直在0
我有下面的代码,但不知道如何调试,也不知道哪里出了问题。
我有HTML输入文件
<input type="file" name="wh_image_upload" id="wh_image_upload" multiple="false" />
和用于AJAX请求的本地化脚本
$img_nonce = wp_create_nonce(\'image_upload_nonce\');
wp_localize_script( \'ajax-script\', \'ajax_image\', array( \'ajax_url\' => admin_url( \'admin-ajax.php\' )) );
和PHP函数
function write_here_featured_image_upload() {
var_dump($_FILES);
die();
}
add_action( \'wp_ajax_write_here_img_upload\', \'write_here_featured_image_upload\' );
add_action( \'wp_ajax_nopriv_write_here_img_upload\', \'write_here_featured_image_upload\' );
JS公司
// Featured image upload AJAX
$("#wh_image_upload").change(function(){
var userFile = new FormData();
var fileInput = $( "#wh_image_upload" )[0].files[0];
//console.log(fileInput);
userFile.append("file", fileInput);
userFile.append("action", "write_here_img_upload");
$.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: userFile,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
},
success: function(data) {
console.log("Image Uploaded! " + data);
}
});
});
我收到一条带有响应的AJAX成功消息
0
.
Image Uploaded! 0
Update我更新了我的工作代码。
最合适的回答,由SO网友:Howdy_McGee 整理而成
WordPress具有中定义的常量
wp-config.php
您可以将错误打印到屏幕上,并将其记录在位于
/wp-content/debug.log
. 看起来是这样的:
define( \'WP_DEBUG\', true );
define( \'WP_DEBUG_DISPLAY\', true );
define( \'WP_DEBUG_LOG\', true );
然后,您可以在特定点将自己的信息打印到调试日志中,并找出函数出错的确切位置(或者函数是否被击中):
function write_here_featured_image_upload() {
error_log( \'Made it into the Ajax function safe and sound!\' );
/** ... Rest of your code ... **/
}
查看开发工具控制台,当今几乎所有浏览器都有
Developer Tools 和a
Console 其中Javascrpit错误输出到。如果您在开发工具控制台中看到错误,那么首先需要修复该错误。
作为一种可能的解决方案,您有这样一个条件,即阻止您在网站前端运行ajax:
if ( is_admin() ) {
add_action( \'wp_ajax_write_here_img_upload\', \'write_here_featured_image_upload\' );
add_action( \'wp_ajax_nopriv_write_here_img_upload\', \'write_here_featured_image_upload\' );
}
功能
is_admin()
告诉WordPress
only 只要在管理面板/仪表板中运行这些操作,您就永远不会看到网站前端发生任何事情。尝试删除条件并按原样添加操作:
add_action( \'wp_ajax_write_here_img_upload\', \'write_here_featured_image_upload\' );
add_action( \'wp_ajax_nopriv_write_here_img_upload\', \'write_here_featured_image_upload\' );