【发布时间】:2014-01-25 09:20:51
【问题描述】:
我的目标是使用 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 新手,如果问题非常基本,请见谅。
【问题讨论】:
-
为什么不使用标准的 http 结果代码,而不是在协议之上重新发明一个协议?
-
感谢 njzk2 - 正如我所说,我对 AJAX 很陌生。你有没有机会提供一个例子来说明如何做到这一点?
-
将响应编码为 JSON 对象。查看 PHP 中的
json_encode和 JavaScript 中的JSON.parse。 -
使用php.net/manual/en/function.http-response-code.php设置失败码,进入ajax报错功能。
-
njzk - 谢谢,我去看看
标签: javascript php jquery ajax wordpress