有人可以帮我把这个包裹一下吗? 我正在尝试以模式方式加载WordPress帖子(自定义帖子类型)标题/内容,但仍在努力使其正确。我是php和ajax的新手,所以我从不同的教程中挑选了一些代码,然后尝试将它们组装在一起。
所以首先我添加一个路径来本地化脚本:
wp_localize_script( 'darkam_global', 'openpost', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
这是我的php函数的样子:
add_action( 'wp_ajax_nopriv_open_post', 'my_open_post' );
add_action( 'wp_ajax_open_post', 'my_open_post' );
function my_open_post() {
$id = $_GET['id'];
$post = get_post($id);
if($post){
wp_send_json(array('post_title' => $post->post_title, 'post_content' => $post->post_content));
} else {
wp_send_json(array('error' => '1'));
}
wp_die();
}
和我的jQuery:
( function( $ ) {
var $modalTrigger = $('.js-modal-trigger');
$modalTrigger.click( open_post_js );
function open_post_js(id) {
jQuery.ajax({
url: openpost.ajaxurl,
type: 'POST',
data: {
id: id,
action: 'open_post'
},
success: function( result ) {
alert( result['post_title'] );
}
})
}
} )( jQuery );
当我触发模式时,出现控制台错误:Uncaught TypeError:无法读取未定义的属性“ type”。警报结果也显示为“未定义”。
任何帮助将不胜感激:)
答案 0 :(得分:1)
在您的php中,您返回{error:1}
的有效响应-但是您无需在jquery / ajax中进行检查。
因此,它可能在php中失败。
在php中失败,因为您没有传递id
。
在click
事件连线中,您拥有:
$modalTrigger.click(open_post_js)
因此单击与调用相同:
open_post_js();
但是您的函数签名是:function open_post_js(id)
,因此它需要一个id
,例如:
open_post_js(1);
然后id
被“传递”到php,但是由于它没有传递给javascript,因此php无法得到它,所以掉下来了。
您如何解决此问题?您需要将id
传递给open_post_js
,或者在id
中检索open_post_js
,例如:
function open_post_js() {
var id=$(this).data("id");
...
}
然后
<div class='js-modal-trigger' data-id="1">...</div>
答案 1 :(得分:1)
您的PHP都看起来不错,问题在于JavaScript中的id
没有赋值。
如果帖子ID是所单击元素上的数据属性,则此方法应该起作用(假设数据属性称为data-id
)
( function( $ ) {
var $modalTrigger = $('.js-modal-trigger');
$modalTrigger.click( open_post_js );
function open_post_js() {
var id = $(this).data('id');
jQuery.ajax({
url: openpost.ajaxurl,
type: 'POST',
data: {
id: id,
action: 'open_post'
},
success: function( result ) {
alert( result['post_title'] );
}
})
}
} )( jQuery );
答案 2 :(得分:0)
您尝试以下代码:
header("Access-Control-Allow-Origin: *");
header( 'Content-Type: application/json;' );
if($post){
wp_send_json(array('post_title' => $post->post_title, 'post_content' => $post->post_content));
} else {
wp_send_json(array('error' => '1'));
}
wp_die();