本文介绍了中止先前的 XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个搜索框,我想在即时输入时显示搜索结果;但是在快速打字时我遇到了问题.

JavaScript:

function CreateXmlHttp() {var xmlhttp;尝试 {xmlhttp = 新的 XMLHttpRequest();}赶上(e){尝试 {xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");}抓住(e){尝试 {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}赶上(e){alert("您的浏览器不支持ajax");返回假;}}}返回xmlhttp;}函数搜索函数(值){如果(值!=''){var xmlhttp = CreateXmlHttp();xmlhttp.open('GET','http://example.com/ajax/instant_search.php?q='+value,true);xmlhttp.send(null);xmlhttp.onreadystatechange=function() {如果(xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById('search_result').innerHTML = xmlhttp.responseText+'<li><a href="http://example.com/search.php?q='+value+'">全搜索<strong>'+value+'';}}} else document.getElementById('search_result').innerHTML = '';}

HTML:

<ul id="search_result"></ul>

如何在新按键时中止先前的 XMLHttpRequest?

解决方案

在这里,我将分享我在我的 stencilsjs 项目中为实现此方案所做的一些概述,

首先,我为我的项目创建了单独的 xmlApi.ts 公共文件,并在其中编写了以下代码

//用于处理 fetch 请求的通用 XMLHttpRequest//当前在搜索组件中使用此 XMLHttpRequest 来获取数据让 xmlApi//创建 XHR 请求const request = new XMLHttpRequest()const fetchRequest = (url: string, params: any) =>{//将其作为 Promise 返回返回新的承诺((解决,拒绝)=> {//设置我们的监听器来处理完成的请求request.onreadystatechange = () =>{//只有在请求完成时才运行if (request.readyState !== 4) { return }//处理响应如果 (request.status >= 200 && request.status < 300) {//如果成功解决(请求)} 别的 {//如果失败拒绝({状态:request.status,statusText: request.statusText})}}//如果出错request.onerror = () =>{拒绝({状态:request.status,statusText: request.statusText})}//设置我们的 HTTP 请求request.open(params.method, url, true)//设置我们的 HTTP 请求头如果(params.headers){Object.keys(params.headers).forEach(key => {request.setRequestHeader(key, params.headers[key])})}//发送请求request.send(params.body)})}xmlApi = {//导出 XMLHttpRequest 对象以在搜索组件中使用以中止先前的 fetch 调用要求,获取请求}导出默认xmlApi

其次,我使用 onTextInput 方法传递了 event 对象以使用 event.target.value

获取输入值

HTML:

{ this.onTextInput(event) }}/>

用于建议的示例 HTML:

这里基于 showSuggestionListFlag ,我已经显示了搜索建议列表,还使用了 css 来正确对齐 div 和输入标签

<ul class="下拉列表">{this.responseData &&this.responseData.map((item, index) => (<li class="list-element">{item} </li>))}

在我的 ts 代码中,我导入了我的 xmlApi

这里我刚刚从我的代码中编写了一些逻辑代码,我还使用了 asyncawait 来处理我的项目代码中的承诺/拒绝,根据您的代码你可以处理自己的承诺/拒绝代码:

从 './xmlApi' 导入 xmlApionTextInput (event) {//首先在这里使用 `event.target.value` 创建 bodydata常量选项 = {方法:'POST',身体:身体数据,标题:{'内容类型':'application/x-www-form-urlencoded;charset=UTF-8'}}尝试 {//中止之前的 xhr 请求调用如果(xmlApi.request){xmlApi.request.abort()}const responseData = xmlApi.fetchRequest(endPointUrl, opts).then(数据=> {consolep.log(`xhr 请求成功`)返回 JSON.parse(data['response'])}).catch(错误=> {console.log.debug(`xhr 请求取消/失败:${JSON.stringify(error)}`)})//使用响应数据if(responseData){this.showSuggestionListFlag = true}}赶上(e){console.log(`获取失败`, e)}}

这是我在 Stack Overflow 上的第一个回答.谢谢!!

I have a search box and I want to display search results while typing instantly; but on fast typing I have problems.

JavaScript:

function CreateXmlHttp() {
    var xmlhttp;
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("your browser doesn't support ajax");
                return false;
            }
        }
    }
    return xmlhttp;
}
function searchfunc(value) {
    if (value!='') {
        var xmlhttp = CreateXmlHttp();
        xmlhttp.open('GET','http://example.com/ajax/instant_search.php?q='+value,true);
        xmlhttp.send(null);
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                document.getElementById('search_result').innerHTML = xmlhttp.responseText+'<li><a href="http://example.com/search.php?q='+value+'">full search for <strong>'+value+'</strong></a></li>';
            }
        }
    } else document.getElementById('search_result').innerHTML = '';
}

HTML:

<input id="search_box" type="text" placeholder="type to search..." onkeyup="searchfunc(this.value)">
<ul id="search_result"></ul>

how can I abort previous XMLHttpRequest on new key presses?

解决方案

Here I am sharing some overview of what I did in my stencilsjs project to achieve this scenario,

firstly I have created the separate xmlApi.ts common file for my project and wrote following code in that

// common XMLHttpRequest for handling fetch request 
// currently using this XMLHttpRequest in search component to fetch the data
let xmlApi
// Create the XHR request
const request = new XMLHttpRequest()
const fetchRequest = (url: string, params: any) => {
// Return it as a Promise
 return new Promise((resolve, reject) => {
// Setup our listener to process compeleted requests
request.onreadystatechange = () => {

  // Only run if the request is complete
  if (request.readyState !== 4) { return }

  // Process the response
  if (request.status >= 200 && request.status < 300) {
    // If successful
    resolve(request)
  } else {
    // If failed
    reject({
      status: request.status,
      statusText: request.statusText
    })
  }
}
// If error
request.onerror = () => {
  reject({
    status: request.status,
    statusText: request.statusText
  })
}
// Setup our HTTP request
request.open(params.method, url, true)

// Setup our HTTP request headers
if (params.headers) {
  Object.keys(params.headers).forEach(key => {
    request.setRequestHeader(key, params.headers[key])
  })
}

   // Send the request
   request.send(params.body)
 })
}
xmlApi = {
// exporting XMLHttpRequest object to use in search component to abort the previous fetch calls
  request,
  fetchRequest
}
export default xmlApi

Second I have passed the event object with onTextInput method to get the input value using event.target.value

HTMl:

<input id="search_box" type="text" placeholder="type to search..." 
      onInput={event => { this.onTextInput(event) }}/>

Sample HTML for suggestion :

Here based on the showSuggestionListFlag ,i have shown the search suggestionlist, also used css to align div and input tag properly

<div class={'search-result ' + (this.showSuggestionListFlag ? 'show' : '')}>
      <ul class="dropdown-list">
        {this.responseData && this.responseData.map((item, index) => (
          <li class="list-element">{item} </li>
        ))}
      </ul>
    </div>

Third in my ts code, i imported the my xmlApi

Here i have just written some logic code from my code, I have also used async and await to handle promise/reject in my project code, according to your code you can handle your own promise/reject code:

import xmlApi from './xmlApi'
onTextInput (event) { // first created bodydata here using `event.target.value`
const opts = {
  method: 'POST',
  body: bodyData,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
}
try {
  // aborting the previous xhr request call
  if (xmlApi.request) {
    xmlApi.request.abort()
  }
  const responseData = xmlApi.fetchRequest(endPointUrl, opts)
    .then(data => {
      consolep.log(`xhr request success`)
      return JSON.parse(data['response'])
    })
    .catch(error => {
      console.log.debug(`xhr request cancelled/failed : ${JSON.stringify(error)}`)
    }) //use responseData
if(responseData){this.showSuggestionListFlag = true}
} catch (e) {
  console.log(`fetch failed`, e)
}
}

This is my first answer on Stack Overflow.Thanks!!

这篇关于中止先前的 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 04:59