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 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable