当前位置:   article > 正文

php后端通过ajax接口返回二进制数据流,让前端下载excel文件(ajax传递json参数)

php后端通过ajax接口返回二进制数据流,让前端下载excel文件(ajax传递json参数)

在这里插入图片描述

   //导出数据
    function exportUser() {
        var url = '?m=User&a=userDeal&act=exportUser';
        var data = JSON.stringify({
            'user_province':$('#province').val(),
            'user_city': $('#city').val(),
            'user_area': $('#area').val(),
            'user_depart': $('#user_depart').val(),
            'user_offices': $('#user_offices').val(),
            'user_auth': $('#user_auth').val(),
            'smallMajor': $('#smallMajor').val(),
            'threeMajor': $('#threeMajor').val(),
            'user_title': $('#user_title').val(),
            'user_name': $('#user_name').val(),
            'user_eid': $('#user_eid').val(),
            'member_type': $('#member_type').val(),
            'user_phone': $('#user_phone').val()
        });
        //console.log(data);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        // 设置请求头,告知服务器请求体的内容类型
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.responseType = "blob";    // 返回类型blob
        // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
  /*      xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // 请求完成且成功,处理响应
                console.log(xhr.responseText); // 打印服务器返回的数据
            }
        };*/
       xhr.onload = function () {
            // 请求完成
            if (this.status === 200) {
                // 返回200
                var blob = this.response;
                var reader = new FileReader();
                reader.readAsDataURL(blob);    // 转换为base64,可以直接放入a标签href
                reader.onload = function (e) {
                    console.log(e);
                    var a = document.createElement('a');
                    a.download = 'data.xls';
                    a.href = e.target.result;
                    $("body").append(a);    // 修复firefox中无法触发click
                    a.click();
                    $(a).remove();
                }
            }
        };
        xhr.send(data);// 发送ajax请求
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

在上面的POST请求示例中,使用JSON.stringify()方法将JavaScript对象转换为JSON格式的字符串,然后设置Content-Type请求头为application/json,最后调用xhr.send(jsonData)发送数据。

注意事项

  • 异步请求(第三个参数为true)是默认的,也是通常推荐的方式,因为它不会阻塞浏览器的UI线程。
  • 当使用XMLHttpRequest时,请确保处理各种可能的错误情况,例如网络错误、服务器错误等。
  • 现代的前端开发中,fetch API通常被视为更现代、更简洁的方式来发送HTTP请求,它基于Promises,提供了更好的错误处理和更强大的功能。然而,XMLHttpRequest在一些旧版浏览器或特定场景中仍然有用。
  • 在处理服务器响应时,请注意检查状态码(xhr.status)和响应类型(xhr.responseText 或xhr.response,取决于响应类型)。如果服务器返回的是JSON数据,你可能需要使用JSON.parse()来解析响应文本。

后端处理

当从前端通过XMLHttpRequest(XHR)的xhr.send(data)方法发送数据到PHP后端时,PHP可以通过 P O S T 或 _POST或 POST_REQUEST(或file_get_contents(‘php://input’),对于非表单编码的数据)来访问这些数据。

然而,如果是通过xhr.setRequestHeader(‘Content-Type’, ‘application/json’)设置了请求头,并使用JSON.stringify(data)将数据转换为JSON字符串发送,那么默认情况下PHP不会将JSON字符串解析到$_POST数组中。

为了获取JSON数据,您需要在PHP后端中读取原始输入流(php://input),并使用json_decode()函数将其解析为PHP对象或数组。

//导出用户信息
    case "exportUser";
        require_once "libs/user.export.php";
        $data = json_decode(file_get_contents('php://input'), true);
        $user_province = $data['user_province'];
        $user_city = $data['user_city'];
        $user_area = $data['user_area'];
        $user_depart = $data['user_depart'];
        $user_name = $data['user_name'];
        $user_offices = $data['user_offices'];
        $user_title = $data['user_title'];
        $user_phone = $data['user_phone'];
        $user_auth = $data['user_auth'];
        $smallMajor = $data['smallMajor'];
        $threeMajor = $data['threeMajor'];
        $member_type = $data['member_type'];
        //筛选数据
        $sql = "SELECT * FROM " . $db->table('user') . " WHERE 1";
        if ($user_depart != "") {
            $sql .= " and user_depart like '%" . $user_depart . "%'";
        }
        if ($user_province != "") {
            $sql .= " and user_province like '%" . $user_province . "%'";
        }
        if ($user_city != "") {
            $sql .= " and user_city like '%" . $user_city . "%'";
        }
        if ($user_area != "") {
            $sql .= " and user_area like '%" . $user_area . "%'";
        }
        if ($user_name != "") {
            $sql .= " and user_name like '%" . $user_name . "%'";
        }
        if ($user_offices != "") {
            $sql .= " and user_offices like '%" . $user_offices . "%'";
        }
        if ($user_title != "") {
            $sql .= " and user_title = '" . $user_title . "'";
        }
        if ($user_phone != "") {
            $sql .= " and user_phone like '%" . $user_phone . "%'";
        }
        if ($user_auth != "") {
            $sql .= " and user_auth = " . $user_auth;
        }
        if ($smallMajor != "") {
            $sql .= " and smallMajor like '%" . $smallMajor . "%'";
        }
        if ($threeMajor != "") {
            $sql .= " and threeMajor like '%" . $threeMajor . "%'";
        }
        if ($member_type != "") {
            $sql .= " and member_type = " . $member_type;
        }
        $sql .= " ORDER BY user_id DESC";
        $row = $db->queryall($sql);
        //操作日志;
        $filesName = "用户信息表" . date("Y.m.d");
        //var_dump($data);
        expExcel($row, $filesName);
        break;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

@漏刻有时

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号