我正在尝试进行简单的ajax调用,将图像的url发送到php函数,该函数将获取附件ID和图像替代文本并将其返回到我的javascript,然后将附件的替代文本添加到html。
我的代码似乎不起作用。 ajax调用成功响应始终为0.
这是我的代码:
叠加image.js
jQuery(document).ready(function(){
jQuery('.block a img').click(function(e){
e.preventDefault();
imgUrl = jQuery(this).parent().attr('href');
altText = '';
jQuery.ajax({
type: 'POST',
url: my_ajax_stuff.ajaxurl,
data: ({action : 'ajax_get_image_id_from_url', imgurl: imgUrl}),
success: function(response) {
altText = response;
alert(response);
}
});
jQuery('#overlay').html('<div id="popup"><div id="popup2"><img src="' + imgUrl + '"><div id="image-caption">' + altText + '</div></div></div>');
jQuery('#overlay').fadeIn();
});
});
functions.php(只有一节)
function enable_ajax_in_wordpress()
{
wp_enqueue_script( 'function', get_template_directory_uri().'/js/overlay-image.js', array('jquery'), true);
wp_localize_script( 'function', 'my_ajax_stuff', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('template_redirect', 'enable_ajax_in_wordpress');
add_action('wp_enqueue_scripts', 'enable_ajax_in_wordpress');
//this function takes a image or any attachment url as the only argument and returns the attachement id
function get_image_id_from_url()
{
$image_url = $_POST['imgurl'];
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
$altText = get_post_meta($attachment[0], '_wp_attachment_image_alt', true);
echo 'test text that - this should be the response of my ajax';
die();
}
add_action("wp_ajax_nopriv_get_image_id_from_url", "get_image_id_from_url");
add_action("wp_ajax_get_image_id_from_url", "get_image_id_from_url");
所以我读了很多次我的代码,但我仍然无法弄清楚为什么我的javascript ajax成功响应仍为0。
任何建议或帮助都将不胜感激。
答案 0 :(得分:2)
您正在调用错误的操作,它是get_image_id_from_url
。
我一直看到并使用jQuery.post
代替jQuery.ajax
。以下作品:
jQuery.post(
my_ajax_stuff.ajaxurl,
{action : 'get_image_id_from_url', imgurl: imgUrl},
function(response) {
console.dir(response);
}
);
以下内容不正确,可以删除:
add_action('template_redirect', 'enable_ajax_in_wordpress');
还有:
wp_create_nonce
,wp_send_json_error
和wp_send_json_success
更好地处理PHP响应。检查以下Q&amp; A是否有完整/全面的方法:How to Use AJAX in a WordPress Shortcode?