javascript - 将变量从 PHP 传递到 AJAX 成功函数

标签 javascript php jquery ajax wordpress

我的目标是使用 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 中的成功函数。

  1. 谁能告诉我如何将 $response $error 传递给我脚本的成功函数?
  2. 我应该采用更好的方法吗?

我是 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/

相关文章:

javascript - 通过修改arr[1][0]多个单元格被修改

javascript - 固定的滚动顶部菜单不允许到达屏幕底部

javascript - Codeigniter - 如何将 JSON 传递到 Assets 文件夹中的 JS 文件?

php - OO数据库类

javascript - 如何从网站网址获取图像并将所有图像存储在 PC 的文件夹中?

javascript - 将服务连接到现有的 meteor 帐户

Javascript 的 Shift right with zero-fill operator (>>>) 产生意想不到的结果

php - Guzzle 使用嵌套数组发布多部分请求

javascript - 单选按钮未正确验证

jquery - 如何正确编码 Joomla MVC 组件以执行 jQuery AJAX GETS/POSTS?