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

hen*_*ght 4 javascript php ajax wordpress jquery

我的目标是使用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 );
    }       
});
Run Code Online (Sandbox Code Playgroud)

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的$response,我的PHP函数中的变量正在传递给我的脚本中的success函数,并且值$response显示在页面上.

我想修改我的成功函数来做这样的事情:

success: function( data ) {
    if( $error == 'true' ) {
        // do something
    } else {
        // do something else
    }
},
Run Code Online (Sandbox Code Playgroud)

问题是,我无法将PHP函数中的$response$error变量传递给我的scipt中的success函数.

  1. 任何人都可以让我知道如何传递$response $error我的脚本的成功功能?
  2. 我应该采取更好的方法吗?

我对AJAX很新,请原谅我,如果这个问题非常基础的话.

tax*_*ala 10

你应该将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);

}
Run Code Online (Sandbox Code Playgroud)

然后,在您的JavaScript代码中:

success: function( data ) {
    if( data.status == 'error' ) {
        // error handling, show data.message or what you want.
    } else {
        // same as above but with success
    }
},
Run Code Online (Sandbox Code Playgroud)

  • 如果你不添加数据类型,jquery将不知道它是否是json.您也可以使用`header('content-type:text/json');`在PHP脚本的顶部执行此操作 (2认同)