我的目标是使用AJAX更新WordPress帖子。到目前为止,我的代码:
脚本:
$.ajax({
type: 'POST',
url: ajax_url,
data: {
'action': 'wp_post',
'ID': post_id,
'post_title': post_title
},
success: function( data ) {
$( '.message' )
.addClass( 'success' )
.html( data );
},
error: function() {
$( '.message' )
.addClass( 'error' )
.html( data );
}
});
PHP:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
if ( $id == 0 ) {
$error = 'true';
$response = 'This failed';
echo $response;
} else {
$error = 'false';
$response = 'This was successful';
echo $response;
}
}
如您所见$response
,我的PHP函数中的变量正在传递给脚本中的成功函数,并且的值$response
显示在页面上。
我想修改我的成功函数以执行以下操作:
success: function( data ) {
if( $error == 'true' ) {
// do something
} else {
// do something else
}
},
问题是,我在将PHP函数中的$response
和和$error
变量都传递给scipt中的成功函数时遇到了麻烦。
$response
和 $error
我的剧本的成功的功能?我是AJAX的新手,如果问题很基本,请原谅我。
您应该将php脚本的响应编码为json,如下所示:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
然后,在您的JavaScript代码中:
success: function( data ) {
if( data.status == 'error' ) {
// error handling, show data.message or what you want.
} else {
// same as above but with success
}
},
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句