首页 > 编程语言 >JavaScript: XMLHTTPRequest

JavaScript: XMLHTTPRequest

时间:2023-05-08 13:45:47浏览次数:40  
标签:readyState XMLHTTPRequest log JavaScript xhr console XMLHttpRequest response

 

XMLHttpRequest (javascript.info)

<body>
    <script>
        // Create a new XMLHTTPRequest object
        let xhr = new XMLHttpRequest()
        xhr.timeout = 5000  // timeout in ms
        let url = new URL('https://cursive.winch.io/cookie.png')
        url.searchParams.set('q', 'test me!')  // https://cursive.winch.io/cookie.png?q=test+me%21
        // Configure
        xhr.open('GET', url)
        // Send the request over the network
        xhr.send()
        // This will be called after the request is complete (even if HTTP status is like 400 or 500), and the response is fully downloaded
        xhr.onload = function () {
            if(xhr.status != 200) {
                console.log(`Error: ${xhr.status}: ${xhr.statusText}`)
            } else {
                console.log(`Done: ${xhr.response} bytes`)
            }
        }
        // When the request couldn't be made, e.g. network down or invalid URL https mistach
        xhr.onerror = function () {
            console.log('onerrror')
        }
        // Triggers periodcally while the response is being downloaded, reports how much has been downloaded
        xhr.onprogress = function (event) {
            // event.loaded - how many bytes downloaded
            // event.lengthComputable = true if the server sent Content-Length header
            // event.total - total number of bytes (if lengthComputable)
            if(event.lengthComputable) {
                console.log(`Received ${event.loaded} of ${event.total} bytes`)
            } else {  // no Content-Length
                console.log(`Received ${event.loaded} bytes`)
            }
        }
        xhr.onreadystatechange = function () {
            console.log(xhr.readyState, 55)
            if(xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED)
                console.log('HEADERS_RECEIVED')
            else if(xhr.readyState === XMLHttpRequest.LOADING)
                console.log('LOADING')
            else if(xhr.readyState === XMLHttpRequest.DONE)
                console.log('Done')
        }
    </script>
</body>

 

setup

 

 

Response Type

 

<body>
    <script>
        let xhr = new XMLHttpRequest()
        xhr.open('GET', 'http://cursive.winch.io:3000/xhr')
        xhr.responseType = 'json'
        xhr.send()
        xhr.onload = function () {
            console.log(typeof this.response)
            console.log(this.response)
        }
    </script>
</body>

 

测试发现json,任何Content-Type都能解析, document可不设置或必须正确设置

 

Synchronous 绑定事件需在send前, 否则 事件绑定无效

 

<body>
    <script>
        console.log('start')
        // 1. 创建ajax对象 synchronous
        const xhr = new XMLHttpRequest()
        // 2. 配置请求信息, synchronous
        xhr.open('get', 'http://cursive.winch.io:3000/xhr', async = false)
        // 4. 发送请求
        xhr.send()
        // 3. 绑定事件
        xhr.onload = function () {
            console.log('xhr.onload', this)
            console.log(JSON.parse(this.response))
        }
        console.log('end')
    </script>
</body>

 

ReadyState

<body>
    <script>
        /**
         * readyState == 0 创建ajax对象成功, XMLHTTPRequest.UNSENT, initial state
         * readyState == 1 配置请求信息完成, XMLHTTPRequest.OPENED, open called
         * readyState == 2 响应报文回到了浏览器, XMLHTTPRequest.HEADERS_RECEIVED, response headers received
         * readyState == 3 浏览器正在解析响应报文, XMLHTTPRequest.LOADING, response is loading (a data packet is received)
         * readyState == 4 解析响应报文成功, 可使用xhr.response, XMLHTTPRequest.DONE, request complete
         *
         * 同步时, 只有 0 1 4 没有 2 3 状态
         * 异步时 0 1 2 3 4
         */
        const xhr = new XMLHttpRequest()
        console.info(`xhr.readyState = ${xhr.readyState} UNSENT`)  // 0
        xhr.open('get', 'https://cursive.winch.io:/cookie.png', async = true)
        console.info(`xhr.readyState = ${xhr.readyState} OPENED`)  // 1
        xhr.onreadystatechange = function () {
            console.info(`xhr.readyState = ${xhr.readyState}`)  // 1
            if(xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED)
                console.info(`xhr.readyState = ${xhr.readyState} HEADERS_RECEIVED`)  // 1
            else if(xhr.readyState === XMLHttpRequest.LOADING)
                console.info(`xhr.readyState = ${xhr.readyState} LOADING`)  // 1
            else if(xhr.readyState === XMLHttpRequest.DONE)
                console.info(`xhr.readyState = ${xhr.readyState} DONE`)  // 1
        }
        xhr.send()

    </script>
</body>

 

Aborting Request

 

标签:readyState,XMLHTTPRequest,log,JavaScript,xhr,console,XMLHttpRequest,response
From: https://www.cnblogs.com/dissipate/p/17381466.html

相关文章

  • Python 和 JavaScript 的区别是什么?
    Python和JavaScript是两门非常流行的编程语言,它们各自有着独特的特点和应用场景。Python和JavaScript是两种不同的编程语言,它们的设计目标和应用场景有所不同。Python是一种多用途、高级、解释型的编程语言,可用于开发各种应用程序,包括Web开发、数据分析、人工智能、科学计算......
  • JavaScript原生兼容大全-持续更新
    JavaScript兼容-持续更新1.css非行内样式操作//currentStyle用于IE低版本getComputed用于主流浏览器//element目标元素attribute目标属性functiongetStyle(element,attribute){returnelement.currentStyle?element.currentStyle(attribute):getComputed(el......
  • JavaScript fromCharCode() 方法
    fromCharCode()方法返回指定的Unicode编码对应的字符。语法格式:String.fromCharCode(n1,n2,...)参数:n1,n1,..表示指定的Unicode编码。示例:(1)返回指定Unicode编码的字符:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8">&......
  • JavaScript 笔记
    JavaScript简介JavsScript于1995年由BrendanEich用时10天写出,用于网景浏览器。最初的名字叫LiveScript,也被部分员工称为Mocha。那时Java语言很流行,出于商业化的考量,更名为JavaScript,但两者之间没有关联。最早的JS作为脚本语言给浏览器增加一些诸如鼠标跟随等交......
  • 使用 JavaScript连接Oracle 数据库(js连接oracle)
    原文链接 在建立Web交互应用程序时,一般使用JavaScript语言作为表现层,而Oracle作为背后真正的数据库。连接JavaScript和Oracle数据库需要一组技术,可以实现将JavaScript执行的数据请求发送到服务器上的Oracle数据库,这样就可以访问和操作Oracle数据库中的相关内容。 在建立Web......
  • JavaScript实训
    程序结构分支结构if分支任务1设计程序界面如下图所示,在文本框输入整数,使用if分支,先判断它是否是数字,如果是,再判断它的奇偶性,结果在弹出窗口(alert)中显示。提示:isNaN(<字符串>)用来判断<字符串>是否不是数字,如果不是数字,该函数返回true,否则返回false。点击查看代码<!D......
  • JavaScript封装大全
    JavaScript封装大全-持续更新Ajax封装//使用该封装需注意//Ajax(method(默认GET),url(网址必传),success(res){(成功时数据处理函数必传)},error(res)(失败时数据处理函数),data(网址中qurey部分用对象形式存储默认为空))//使用ES6语法classAjax{//解构传......
  • javaScript 常用去除 ‘console
    javaScript常用去除‘console.log’办法手动注释掉console.log语句:可以手动在代码中注释掉所有console.log语句,但是这种方法比较繁琐,并且需要手动维护,不太适合大型项目。使用Babel插件去除console.log:Babel是一个JavaScript编译器,它可以将ES6+的代码转换成......
  • JavaScript 面试题
    一、event.stopPropagation和 event.preventDefault的区别1、event.stopPropagation(停止传播)   用于阻止捕获和冒泡事件的进一步传播。但是不能阻止同一Dom节点上的其它事件被调用。2、event.preventDefault(阻止默认)   方法可防止元素的默认行为。比如a标签的......
  • 实践分享:打造极具高扩展性的JavaScript SDK
    SDK(SoftwareDeveloperKit)是使用FeatureProbe服务必不可少的工具之一。SDK能将用户的应用程序连接到FeatureProbe服务,根据用户的配置获取开关的结果,还能将开关的访问情况上报给FeatureProbe,进而实现A/B实验的能力。FeatureProbe目前对外提供十余种主流开发语言的SDK,包括......