我正在尝试提交一个Ajax调用,将所选图像的源URL从WordPress媒体库传输到我的插件设置页面中的PHP。单击“保存”后,我经常会遇到“错误,错误请求”。尝试调用我的AJAX URL时的状态400。
我的AJAX URL当前是domain/wp-admin/admin-AJAX。确实存在的php。我曾尝试设置AJAX调用应该期望的多种数据类型,但我遇到了相同的错误。
如果在javascript中删除AJAX调用的URL部分,它确实会导致success函数,但success的参数“response”由页面的HTML组成,而不是我想要传输的数据。
HTML
<form method=\'post\'>
<div class=\'image-preview-wrapper\'>
<img id=\'image-preview\' src=\'<?php echo wp_get_attachment_url( get_option( \'media_selector_attachment_id\' ) ); ?>\' height=\'100\'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( \'Upload image\' ); ?>" />
<input type=\'hidden\' name=\'image_attachment_id\' id=\'image_attachment_id\' value=\'<?php echo get_option( \'media_selector_attachment_id\' ); ?>\'>
<input type="submit" name="submit_image_selector" value="Save" id="saveMediaButton" class="button-primary">
</form>
通过enques加载Javascript
function enqueue_my_scripts() {
wp_enqueue_script( \'media-library\', plugins_url( \'/media-library.js\', __FILE__ ), array(), \'1.0.0\', true );
wp_localize_script( \'media-library\', \'my_ajax_object\', array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'admin_enqueue_scripts\', \'enqueue_my_scripts\' );
通过单击ID\'ed submitMediaButton按钮调用的JavaScript
$(\'#saveMediaButton\').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "html",
url: my_ajax_object.ajax_url,
data: {
image_attachment_id: document.getElementById("image-preview").getAttribute(\'src\')
},
success: function(response) {
var jsonData = response;
console.log(response);
console.log(document.getElementById("image-preview").getAttribute(\'src\'));
},
error: function(jqxhr, textStatus, errorThrown) {
console.log(my_ajax_object.ajax_url);
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
}
});
});
最合适的回答,由SO网友:Milan Hirpara 整理而成
您好,请尝试以下代码
jquery:
$(\'#saveMediaButton\').click(function(e) {
e.preventDefault();
$.ajax({
url : my_ajax_object.ajax_url,
type : \'post\',
data : {
action : \'action_upload_img\',
image_attachment_id : document.getElementById("image-preview").getAttribute(\'src\')
},
dataType : \'html\',
success : function( response ) {
var jsonData = response;
console.log(response);
console.log(document.getElementById("image-preview").getAttribute(\'src\'));
},
error : function(jqxhr, textStatus, errorThrown) {
console.log(my_ajax_object.ajax_url);
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
},
});
});
PHP代码:
add_action( \'wp_ajax_action_upload_img\', \'action_upload_img\' );
add_action( \'wp_ajax_nopriv_action_upload_img\', \'action_upload_img\' );
function action_upload_img(){
$response = [];
$response[\'data\'] = $_POST;
//Your code
update_option( \'media_selector_attachment_id\', $_POST["image_attachment_id"] );
wp_send_json( $response );
wp_die();
}