为什么jQuery中的AJAX无法接收来自PHP的JSON字符串?

12 浏览
0 Comments

为什么jQuery中的AJAX无法接收来自PHP的JSON字符串?

感谢查看我的问题。首先,我知道这不是第一次有人提出这样的问题,但我已经阅读StackOverflow超过3个小时了...还是无法弄清楚。\n要点如下:\n我试图使用json_encode从messaging.php将值发送到messaging.js。\n以下是messaging.php的代码:\n

prefix . 'none_of_ur_business';
if(isset($to) && isset($to) && isset($to)):
$wpdb->insert(
    $table_name,
    array(
        'notit_sender_userid' => $current_user->display_name,
        'notit_receiver_userid' => $to,
        'notit_subject' => $subject,
        'notit_message' => $message
    )
);
$testtext = 'does this work??';
echo json_encode(array('test' => $testtext));
endif;
?>

\n以下是messaging.js的代码:\n

function sendMessage(uname, subject, message){
  $.ajax({
    url : wp_directory+'/modules/messaging/messaging.php',
    dataType : 'JSON',
    type : 'post',
    data: {
         'uname' : uname,
         'subject' : subject,
         'msg' : message
     },
     success: function(data) {
         alert(data.test);
     }
  });
}

\n一些相关的事项:\n- 我正在WordPress平台上开发\n- 我使用messaging.php将数据发送到我的数据库(也许这就是为什么它不起作用的原因?)\n我无法从ajax success函数中获取任何东西,它从未“弹出”。\n请提供任何您能提供的帮助,我将非常感激!

0
0 Comments

在WordPress中,您正在尝试单独访问文件(messaging.php),并且在messaging.php中使用了错误的“global $wpdb;”语句。首先,您应该包含必要的WordPress文件。将以下代码添加到您的messaging.php文件中:

define( 'SHORTINIT', true );
require( '{wp_root}/wp-load.php' );

请更改{wp_root}。如果您的WordPress安装在服务器根目录上,则应该像$_SERVER["DOCUMET_ROOT"]这样写,或者您可以手动调整。

有关更多信息,请查看此页面:Using WPDB in standalone script?

0