Reading binary data using jQuery Ajax

jQuery is an excellent tool to make web development easy and straightforward. It helps while doing DOM manipulation and makes Ajax requests painless across different browsers and platforms. But if you want make an Ajax request, which is giving binary data as a response, you will discover that it does not work for jQuery, at least for now. Changing “dataType” parameter to “text”, does not help, neither changing it to any other jQuery supported Ajax data type.

Problem here is that jQuery still does not support HTML5 XMLHttpRequest Level 2 binary data type requests – there is even a bug in jQuery bug tracker, which asks for this feature. Although there is a long discussion about this subject on the GitHub, it seems that this feature will not become part of jQuery soon.

To find a solution for this problem, we have to modify XMLHttpRequest itself. To read binary data correctly, we have to treat response type as blob data type.

var xhr = new XMLHttpRequest();
xhr.open(‘GET‘, ‘/my/image/name.png‘, true);
xhr.responseType = ‘blob‘;

xhr.onload = function(e) {
  if (this.status == 200) {
    // get binary data as a response
    var blob = this.response;
  }
};

xhr.send();

But what happens if we have to directly modify received binary data? XHR level 2 also introduces  “ArrayBuffer” response type. An ArrayBuffer is a generic fixed-length container for binary data. They are super handy if you need a generalized buffer of raw data, but the real power is that you can create “views” of the underlying data using JavaScript typed arrays.

var xhr = new XMLHttpRequest();
xhr.open(‘GET‘, ‘/my/image/name.png‘, true);
xhr.responseType = ‘arraybuffer‘;

xhr.onload = function(e) {
  // response is unsigned 8 bit integer
  var responseArray = new Uint8Array(this.response);
};

xhr.send();

This request creates an unsigned 8-bit integer array from data buffer. ArrayBuffer is especially useful if you have to read data for WebGL project,WebSocket or Canvas 2D

Binary data ajax tranport for jQuery

Sometimes making complete fallback to XMLHttpRequest is not a good idea, especially if you want to keep jQuery code clean and understandable. To solve this problem, jQuery allows us to create Ajax transports – plugins, which are created to make custom Ajax requests.

Our idea is to make “binary” Ajax transport based on our previous example. This Ajax transport creates new XMLHttpRequest and passes all the received data back to the jQuery.

/**
 *
 * jquery.binarytransport.js
 *
 * @description. jQuery ajax transport for making binary data type requests.
 * @version 1.0
 * @author Henry Algus <[email protected]>
 *
 */

// use this transport for "binary" data type
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == ‘binary‘)) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
    {
        return {
            // create new XMLHttpRequest
            send: function(headers, callback){
		// setup all variables
                var xhr = new XMLHttpRequest(),
		url = options.url,
		type = options.type,
		async = options.async || true,
		// blob or arraybuffer. Default is blob
		dataType = options.responseType || "blob",
		data = options.data || null,
		username = options.username || null,
		password = options.password || null;

                xhr.addEventListener(‘load‘, function(){
			var data = {};
			data[options.dataType] = xhr.response;
			// make callback and send data
			callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, async, username, password);

		// setup custom headers
		for (var i in headers ) {
			xhr.setRequestHeader(i, headers[i] );
		}

                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function(){
                jqXHR.abort();
            }
        };
    }
});

For this script to work correctly, processData must be set to false, otherwise jQuery will try to convert received data into string, but fails.

Now it is possible to read binary data using usual jQuery syntax:

$.ajax({
  url: "/my/image/name.png",
  type: "GET",
  dataType: "binary",
  processData: false,
  success: function(result){
	  // do something with binary data
  }
});

If you want receive ArrayBuffer as response type, you can use responseType parameter while creating Ajax request:

responseType:‘arraybuffer‘

How to setup custom headers?

It is possible to set multiple custom headers when you are making the request. To set custom headers, you can use “header” parameter and set its value as an object, which has list of headers:

$.ajax({
          url: "image.png",
          type: "GET",
          dataType: ‘binary‘,
          headers:{‘Content-Type‘:‘image/png‘,‘X-Requested-With‘:‘XMLHttpRequest‘},
          processData: false,
          success: function(result){
          }
});

Another options

Asynchronous or synchronous execution

It is possible to change execution type from asynchronous to synchrous when setting parameter “async” to false.

async:false,

Login with user name and password

If your script needs to have authentication during the request, you can use username and password parameters.

username:‘john‘, password:‘smith‘,

Supported browsers

BinaryTransport requires XHR2 responseType, ArrayBuffer and Blob response type support from your browser, otherwise it does not work as expected. Currently most major browsers should work fine.

Firefox: 13.0+ Chrome: 20+ Internet Explorer: 10.0+ Safari: 6.0 Opera: 12.10

Binary transport jQuery plugin is also available in myGitHub repository.

原文地址:https://www.cnblogs.com/fit/p/9501206.html

时间: 2024-08-26 23:39:11

Reading binary data using jQuery Ajax的相关文章

使用jQuery AJAX读取二进制数据

READING BINARY DATA USING JQUERY AJAX http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/ Query is an excellent tool to make web development easy and straightforward. It helps while doing DOM manipulation and makes Ajax requests painles

jquery ajax实例教程和一些高级用法

jquery ajax的调用方式:jquery.ajax(url,[settings]),jquery ajax常用参数:红色标记参数几乎每个ajax请求都会用到这几个参数,本文将介绍更多jquery ajax实例,后面会有一些ajax高级用法 query ajax的调用方式:jquery.ajax(url,[settings]),因为实际使用过程中经常配置的并不多,所以这里并没有列出所有参数,甚至部分参数默认值,就是最佳实践,根本没必要去自己定义,除非有特殊需求,如果需要所有参数,可以查看jq

jQuery Ajax Post Data Example

http://www.formget.com/jquery-post-data/ jQuery Ajax Post Data Example Fugo Of FormGet jQuery $.post() method is used to request data from a webpage and to display the returned result (sent from requested page) on to that webpage from where the reque

jQuery AJAX Call for posting data to ASP.Net page ( not Get but POST)

the following jQuery AJAX call to an ASP.Net page. $.ajax({ async: true, type: "POST", url: "DocSummaryDataAsync.aspx", //"DocSummary.aspx/GetSummaryByProgramCount", contentType: "application/json; charset=utf-8", d

Django+JQuery+Ajax+Post方案中的问题及解决

遇到的问题 请求发送后,服务端无响应 Django对于POST请求会检查请求来源,表单方式提交时: 在Form内添加 `{% csrf_token %}` 标签: request响应函数前,添加 `@csrf_exempt` ; Jquery POST 方式提交时,在服务端添加了 @csrf_exempt ,在Django1.5版本后,无法直接通过POST获取参数,通过`raw_data = request.body` 获取数据时,出现如下错误提示: Exception: You cannot

jquery ajax 方法及各参数详解

jquery ajax 方法及各参数详解 1.$.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数信息. 参数列表: 参数名 类型 描述 url String (默认: 当前页地址) 发送请求的地址. type String (默认: "GET") 请求方式 ("POST" 或 "GET"), 默认为 "GET".注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分

Django1.7+JQuery+Ajax集成小例子

Ajax的出现让Web展现了更新的活力,基本所有的语言,都动态支持Ajax与起服务端进行通信,并在页面实现无刷新动态交互. 下面是散仙使用Django+Jquery+Ajax的方式来模拟实现了一个验证用户注册时,用户名存在不存在的一个小应用.注意,验证存在不存在使用的是Ajax的方式,不用让用户点击按钮验证是否存在. 截图如下: 页面HTML代码如下: <!DOCTYPE html> <html> <head lang="en"> <meta

JQuery ajax 在aspx中传值和取值

传值:ajax中的data(json)  js代码: <script type="text/javascript"> $(function () { $("#btnAddNews").bind("click", function () { var _name= $.trim($("#txtNewTitle").val()); $.ajax({ type: "POST", url: "A

jquery ajax跨域的完美解决方法(jsonp方式)

ajax跨域请求的问题,JQuery对于Ajax的跨域请求有两类解决方案,不过都是只支持get方式,接下来为大家详细介绍下客户端JQuery.ajax的调用代码 今天在项目中需要做远程数据加载并渲染页面,直到开发阶段才意识到ajax跨域请求的问题,隐约记得Jquery有提过一个ajax跨域请求的解决方式,于是即刻翻出Jquery的API出来研究,发 JQuery对于Ajax的跨域请求有两类解决方案,不过都是只支持get方式.分别是JQuery的 jquery.ajax jsonp格式和jquer