我的目标是使用 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;
}
}
如您所见,我的 PHP 函数中的 $response
变量被传递到脚本中的成功函数,并且 $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
}
},
关于javascript - 将变量从 PHP 传递到 AJAX 成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20975930/