ITeye博客

Ajax Request

Kyll · 2007-09-12 08:18 · ML & Script & Style & Other... · Ajax · Safari · XML · Microsoft · IE · Markdown

js 代码

 

  1. var http_request = false;
  2. function makeRequest(url, queryStr, methodName) {
  3. http_request = false;
  4. if (window.XMLHttpRequest) { // Mozilla, Safari,...
  5. http_request = new XMLHttpRequest();
  6. if (http_request.overrideMimeType) {
  7. http_request.overrideMimeType('text/xml');
  8. }
  9. } else if (window.ActiveXObject) { // IE
  10. try {
  11. http_request = new ActiveXObject("Msxml2.XMLHTTP");
  12. } catch (e) {
  13. try {
  14. http_request = new ActiveXObject("Microsoft.XMLHTTP");
  15. } catch (e) {
  16. }
  17. }
  18. }
  19. if (!http_request) {
  20. alert('Giving up :( Cannot create an XMLHTTP instance');
  21. return false;
  22. }
  23. http_request.onreadystatechange = methodName;
  24. http_request.open('POST', url, true);
  25. http_request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  26. http_request.send(queryStr);
  27. }

readyState的取值如下:

  • 0 (未初始化)
  • 1 (正在装载)
  • 2 (装载完毕)
  • 3 (交互中)
  • 4 (完成)

http_request.responseText 取得 String
http_request.responseXML 取得 Xml

XMLHttpRequest 参考

Methods

Method Description abort() Cancels the current request getAllResponseHeaders() Returns the complete set of http headers as a string getResponseHeader("headername") Returns the value of the specified http header open("method","URL",async,"uname","pswd") Specifies the method, URL, and other optional attributes of a request

The method parameter can have a value of "GET", "POST", or "PUT" (use "GET" when requesting data and use "POST" when sending data (especially if the length of the data is greater than 512 bytes.

The URL parameter may be either a relative or complete URL.

The async parameter specifies whether the request should be handled asynchronously or not. true means that script processing carries on after the send() method, without waiting for a response. false means that the script waits for a response before continuing script processing

send(content) Sends the request setRequestHeader("label","value") Adds a label/value pair to the http header to be sent

Properties

Property Description onreadystatechange An event handler for an event that fires at every state change readyState Returns the state of the object:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

responseText Returns the response as a string responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties status Returns the status as a number (e.g. 404 for "Not Found" or 200 for "OK") statusText Returns the status as a string (e.g. "Not Found" or "OK")

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。