蓬蒿人. 2021-02-26 15:52 采纳率: 83.3%
浏览 56
已结题

一个简单的ajax封装 ,但是什么反应都没有,用其他例子测试过不是服务器问题。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function ajax(options) {
            let xhr = new XMLHttpRequest();
            let params = '';
            for (var attr in options.data) {
                params += attr + '=' + options.data[attr] + '&';   //截取对象形式参数
            }
            params = params.substr(0, params.length - 1);
            if (options.type == 'get') {               //get方法
                options.url = options.url + '?' + params;
            }
            xhr.open(options.type, options.url);
            if (options.type == 'post') {                //post方法
                let content_type = options.header.content_type;
                xhr.setRequestHeader('Content-Type', content_type);//设置数据格式
                if (content_type == 'application/json') {
                    xhr.send(JSON.stringify(options.data));
                }
                else {
                    xhr.send(params);
                }
            }
            else {
                xhr.send();
            }
            xhr.onload = function () {
                if (xhr.status == 200) {
                    options.success(xhr.responseText);
                } else {
                    options.error(xhr.responseText, xhr);
                }

            }

            ajax({
                url: 'http://localhost:3000/get',
                type: 'get',
                data: {
                    name: 'qq',
                    age: 21,
                },
                header: {
                    content_type: 'application/json'  // 'application/x-www-form-urlencoded'
                },
                success: function (data) {
                    console.log('这是success函数' + data);
                },
                error: function (data, xhr) {
                    console.log('这是error函数' + data);
                    console.log(xhr);
                }


            });





        }
    </script>
</body>

</html>

  • 写回答

2条回答 默认 最新

  • 天际的海浪 2021-02-26 21:13
    关注

    你在ajax函数内调用ajax函数,是要递归吗?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月8日
  • 已采纳回答 3月31日

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?