没看到FormData

没看到FormData

<!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 type="module">
        import { ajax, get, getJSON, post } from './module/index.js';
        const url = 'https://www.imooc.com/api/http/json/search/suggest?words=js';
        const xhr = ajax(url, {
        method:'POST',
        params:{
            username:'alex'
        },
        data:{
            age:19
        },
        responseType:'json',
        success(response){
            console.log(response);
        },
        httpCodeError(err){
            console.log('http code error',err);
        },
        error(xhr){
            console.log('error',xhr);
        },
        abort(xhr){
            console.log('abort',xhr);
        },
        timeout(xhr){
            console.log('timeout',xhr);
        },
        })
    </script>
</body>
</html>
// 常量
import { HTTP_GET, CONTENT_TYPE_FORM_URLENCODED, CONTENT_TYPE_JSON } from './constants.js';
// 工具
import { serialize, addURLData, serializeJSON } from "./utils.js";
// 默认参数
import DEFAULTS from "./defaults.js";
// AJAX类
class Ajax {
    constructor(url, options) {
        this.url = url;
        this.options = Object.assign({}, DEFAULTS, options);
        // 初始化
        this.init();
    };
    // 初始化
    init() {
        const xhr = new XMLHttpRequest();
        this.xhr = xhr;
        this.bindEvents();
        xhr.open(this.options.method, this.url + this.addParam(), true);
        // 设置responseType
        this.setResponseType();
        // 设置跨域是否携带Cookie
        this.setCookie();
        // 设置timeoutTime
        this.settimeoutTime();
        // 发送请求
        this.sendData();
    };
    // 处理事件响应函数
    bindEvents() {
        const xhr = this.xhr;
        const { success, httpCodeError, error, abort, timeout } = this.options;
        xhr.addEventListener('load', () => {
            if (this.httpCodeOK()) {
                success(xhr.response, xhr);
            } else {
                httpCodeError(xhr.status, xhr);
            }
        }, false);
        // error
        xhr.addEventListener('error', () => {
            error(xhr);
        }, false);
        // abort
        xhr.addEventListener('abort', () => {
            abort(xhr);
        }, false);
        // timeout
        xhr.addEventListener('timeout', () => {
            timeout(xhr);
        }, false);
    };
    // 检测http状态码是否正常
    httpCodeOK() {
        const xhr = this.xhr;
        return (xhr.status >= 200 && xhr.status < 300) || xhr.status === 305;
    }
    addParam() {
        const { params } = this.options;
        if (!params) {
            return '';
        }
        return addURLData(this.url, serialize(params));
        const url = this.url;
    }
    setResponseType() {
        this.xhr.responseType = this.options.responseType;
    }
    setCookie() {
        if (this.options.withCredentials) {
            this.xhr.withCredentials = true;
        }
    }
    settimeoutTime() {
        const { timeoutTime } = this.options;
        if (timeoutTime > 0) {
            this.xhr.timeout = timeoutTime;
        }
    }
    sendData() {
        const xhr = this.xhr;
        if (!this.isSendData()) {
            return xhr.send(null);
        }

        let resultData = null;
        const {data}=this.options;
        if (this.isFormData) {
            resultData = data;
        } else if (this.isFormURL()) {
            this.setCountentType(CONTENT_TYPE_FORM_URLENCODED);
            resultData = serialize(data);
        } else if (this.isJSONdata()) {
            this.setCountentType(CONTENT_TYPE_JSON);
            resultData = serializeJSON(data);
        } else {
            this.setCountentType();
            resultData = data;
        }
        xhr.send(resultData);

    };
    // 是否需要send发送数据
    isSendData() {
        const { data, method } = this.options;
        if (!data) return false;
        if (method.toLowerCase() === HTTP_GET.toLowerCase()) return false;
        return true;
    }
    ifFormData() {
        return this.options.data instanceof FormData;
    }
    isFormURL() {
        return this.options.contentType.toLowerCase().includes(CONTENT_TYPE_FORM_URLENCODED);
    }
    isJSONdata() {
        return this.options.contentType.toLowerCase().includes(CONTENT_TYPE_JSON);
    }
    setCountentType(CountentType = this.options.contentType) {
        if (!CountentType) {
            return;
        } else {
            this.xhr.setRequestHeader('Content-Type', this.contentType);
        }
    }
    getXHR() {
        return this.xhr;
    }
}

export default Ajax;

相关截图:

https://img1.sycdn.imooc.com//climg/6209cbbf094b10ad33602100.jpg

正在回答

登陆购买课程后可参与讨论,去登陆

2回答

同学你好,设置请求头这里书写有误,建议修改:

https://img1.sycdn.imooc.com//climg/6209d3b40977bfc509540269.jpg

祝学习愉快~

好帮手慕然然 2022-02-14 12:00:42

同学你好,以下代码书写有误导致没有FormData,如图所示

https://img1.sycdn.imooc.com//climg/6209d34f0923036108120168.jpg

另外,以下方法名使用有误:

https://img1.sycdn.imooc.com//climg/6209d3cc094c3d4d09190620.jpg

这部分代码比较多,建议书写时仔细一点,慢一点。

祝学习愉快!


问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师