开发者

Can you use other formats beside XML with XMLHttpRequest?

I understand JSON can be used instead of XMLHttpRequest in Javascript, but can I make requests and get totally arbitrary data back?

Like a custom text or binary format?

Or is the interface limited to jSON and XML?

I hope I get through what I wonder here...

a) How do I create a plain request without XML or JSO开发者_JAVA百科N?

b) How do I access the result (answer) as a plain string, not an object?


Yes, just set the content-type:

var request = new XMLHttpRequest();
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); // whatever character set you need.
request.open("GET", "yourtext.txt", true);
request.onreadystatechange = function() {
 if(this.readyState == 2) {
  alert(request.responseText);
 }
}
request.send();


You can use any text-based format: XML, JSON, CSV, or just text/plain.

I'm not sure what happens if you try to use a binary format.


You can get the result back as

  • An DOM document (if XML was received) using the responseXML property, or
  • A string (regardless of format) using the responseText property

Some browsers can also return it as an object, if it was JSON.

The ability to get back anything as a string allows you parse any format yourself.


You can set the content type explicitly to plain text before send():

var request = new XMLHttpRequest();
request.open("POST", "/test.php");
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.send(message);


In addition to the posts mentioning the setRequestHeader method: it seems like the w3 specifications for the xmlhttprequest API only imposes (suggested) restrictions for the header (i.e. the first argument) but not for the value (i.e. the second argument).

Here's the link to the spec: http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method .

AFAIC, this means any data type is valid as far as the requested transfer is concerned. This does not extend to the returned data however as only text and xml are specified.

I might be wrong though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜