我试图提交一个Ajax调用,将选定图像的源URL从一个WordPress媒体库转移到我的插件设置页面中。在单击“保存”时,我经常会遇到“错误、错误的请求”。当试图调用我的AJAX时,状态400。
我的AJAX当前是域/wp/admin-ajax.php,它确实存在。我尝试设置AJAX调用应该期望的多个数据类型,但遇到了相同的错误。
如果我删除javascript中AJAX调用的URL部分,它确实会导致成功函数,但是成功的参数"response“包含页面的HTML,而不是我希望传输的数据。
HTML
' height='100'>
'>通过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' );在按钮上调用的JavaScript,单击ID‘ID
$('#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);
}
});
});发布于 2019-07-02 04:43:46
嗨,请试试下面的代码
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();
}发布于 2019-07-02 04:45:59
请试试这个:
在数据中添加动作参数。
data: {
action:"this_ajax_action",image_attachment_id: document.getElementById("image-preview").getAttribute('src')
},添加<>Functions.php
add_action( 'wp_ajax_this_ajax_action', 'this_ajax_action_callback' );
add_filter( 'wp_ajax_nopriv_this_ajax_action', 'this_ajax_action_callback');
function this_ajax_action_callback()
{
if(isset($_POST["image_attachment_id"]) && !empty($_POST["image_attachment_id"]));
# here what you want to do with attachment id
$data = "";
echo $data;
die();
}https://wordpress.stackexchange.com/questions/341933
复制相似问题