weixin_33721427 2015-01-17 12:50 采纳率: 0%
浏览 26

如何准备一个文件,以便能够发送响应作为回报?

我对jQueryAjax很陌生,我现在只学会了如何发送Ajax请求。我的问题是如何准备一个文件,以便能够发送响应作为回报?比方说,我的Ajax请求的url是process.php,我如何准备process.php文件,以便接收数据类型html或文本的响应?我知道这个问题听起来很奇怪,但我更关心的是处理响应的方法,而不是发送请求。请帮帮我吧,多谢!

  • 写回答

1条回答 默认 最新

  • weixin_33727510 2015-01-17 13:00
    关注

    Your PHP endpoint will receive the data using e.g. POST (you can use GET if you like).

    Then you need to reply in HTML, JSON, or plain text.

    In the example below, you send $.POST with a data value of, say, { cmd: 'time' }.

    // Read command. No command is equivalent to an empty string.
    $cmd = empty($_POST['cmd']) ? '' : $_POST['cmd'];
    
    // Do something with the command.
    switch($cmd) {
        case '': // Empty string
            $reply = "You asked nothing";
            break;
        case 'time':
            $reply = date('Y-m-d H:i:s');
            break;
        default:
            $reply = "You asked a unexpected question";
            break;
    }
    
    /* Text */
    Header('Content-Type: text/plain;charset=utf8');
    die($reply);
    
    /* HTML */
    Header('Content-Type: text/html;charset=utf8');
    die($reply); // This should contain valid HTML
    
    /* JSON, used to send structured data */
    $reply = array(
        'status' => 'OK',
        'message'=> 'All good',
        'reply'  => $reply,
    );
    Header('Content-Type: application/json;charset=utf8');
    die(json_encode($reply));
    

    In the last case, your callback function will receive an object with members status, message and reply:

    success: function(data) {
        if (!data.status) {
            alert("Unexpected return from AJAX endpoint: " + data);
            return;
        }
        if ('OK' == data.status) {
            alert(data.reply);
            return;
        }
        alert("AJAX signaled error: " + data.message);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)