发送http请求

本文详细解释了如何使用XMLHttpRequest对象发送GET请求到服务器,并在回调函数中处理返回的数据。通过实例演示了从文件phrasebook.txt中获取简单文本内容的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.informit.com/articles/article.aspx?p=669066&seqNum=2

,附内容:

XMLHttp.open("GET", "phrasebook.txt");
XMLHttp.onreadystatechange = handlerFunction;
XMLHttp.send(null);

Sending an HTTP request to a server using XMLHttpRequest consists of the following steps:

  1. Provide the URL and the HTTP verb to use.
  2. Define a callback function when results arrive.
  3. Send the request.

Step 1 can be taken with the open() method of the XMLHttpRequest object. This does not—unlike what the method name suggests—actually open an HTTP connection, but just initializes the object. You provide the HTTP verb to use (usuallyGET or POST) and the URL.

Step 2, the callback function, is provided to the onreadystatechange property of the object. Whenever thereadyState property ofXMLHttpRequest changes, this callback function is called. Finally, thesend() method sends the HTTP request.

In the callback function, the readyState value 4 represents the state of the object we want: call completed. In that case, theresponseText property contains the data returned from the server.

Here is a fully working example, sending a GET request to the server (a file calledphrasebook.txt with simple text content) and evaluating the response of that call:

Sending a GET Request (xmlhttpget.html)
<script language="JavaScript"
  type="text/javascript" src="xmlhttp.js"></script>
<script language="JavaScript"
 type="text/javascript">
var XMLHttp = getXMLHttp();
XMLHttp.open("GET", "phrasebook.txt");
XMLHttp.onreadystatechange = handlerFunction;
XMLHttp.send(null);

function handlerFunction() {
  if (XMLHttp.readyState == 4) {
    window.alert("Returned data: " +
                 XMLHttp.responseText);
  }
}
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值