Coder Social home page Coder Social logo

mmrequest's Introduction

mmRequest

mmRequest 为异步 HTTP(AJAX)请求提供了解决方案。就像 jQuery.ajax() 所做的那样。

mmRequest 是 avalon 三柱臣之一(另外两个是 route 和 animation)。

安装

bower 安装:

bower install mm-request

从npm 安装

npm install mmRequest --save

开始

Avalon 遵循 AMD 规范。在引入 avalon.jsmmRequest.js 之后,你便可以像下面这样使用 mmRequest 了:

require(['./mmRequest'], function(avalon) {
    avalon.ajax({
        url: '/foobar'
    });
});

文档

mmRequest 提供了如下方法:

/*
 * avalon.ajax 需要传入一个拥有类似 url、type、dataType、type 等属性的对象参数;
 * avalon.ajax 的行为类似于 jQuery.ajax。
 */
avalon.ajax(opts)

/*
 * 其他一些简写方法:
 */
avalon.get( url [, data ] [, success(data, textStatus, XHR) ] [, dataType ] )
avalon.post( url [, data ] [, success(data, textStatus, XHR) ] [, dataType ] )
avalon.upload( url, form [,data] [, success(data, textStatus, XHR)] [, dataType])
avalon.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
avalon.getScript( url [, success(script, textStatus, jqXHR) ] )

avalon可以在配置对象使用headers来指定头部, 
```javascript
avalon.ajax({
	type: "POST",
	url: "your-path",
	headers: {
      xxx: "yyy"

   },
   success: function(){}

})

/*

  • 一些有用的工具类方法: */ // 将一个对象转换成一个用于 URL 中传递请求参数的字符串 avalon.param(obj) // 将一个用于 URL 中传递请求参数的字符串转换成一个对象 avalon.unparam(str) // 将一个元素中的表单元素编码成字符串 avalon.serialize(element)

更多信息请参考 `/docs`。

示例
----

安装依赖:

cd demo/ && npm install


如果你很幸运地在**,试试 [cnpm](http://cnpmjs.org/)。

开启服务:

cd ../ && npm start


现在,打开你的浏览器访问 `http://127.0.0.1:3000` 这个地址,你将会看到例子。你可以在 `demo/bin/www` 这个文件中配置端口。

在测试跨域请求之前,你需要模拟一个跨域的环境。你可以将这个项目复制到另外的路径并用另一个端口开启服务作为后端服务(这个例子中,后端服务的端口是 `9000`)。

祝你愉快。:grin:

贡献
------------

请在 `src/` 目录下开发相应的模块。

mmRequest 使用 [gulp](http://gulpjs.com/) 构建,请先安装依赖模块:

npm install


然后开启 `gulp`,监听 `src/` 下的变化并自动合并文件至 `public/`:

gulp


更新日志
------------

见 [CHANGELOG.md](CHANGELOG.md)

mmrequest's People

Contributors

bukede avatar dragonwong avatar ilife5 avatar michaeljayt avatar rubylouvre avatar xuzicn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mmrequest's Issues

关于avalon.ajax跨域

var url='//172.16.7.58:7788/template/search/all';
avalon.ajax({
url:url + '/jsonp?callback=?',
dataType: "jsonp",
data: {},
cache: true
}).done(function(res) {
avalon.log(res);
}).fail(function(jqXHR, textStatus) {
avalon.log(jqXHR );
});

在浏览器network下可以看到返回数据,如:[{id:1},{id:2}],数组类型的字符串,但是程序不走done,只走fail,用jq也是只走error,不走success,应该是跨域的同类问题,请大神瞧瞧。谢谢

ie8报错,且不兼容avalon2.2.7

  • 这里写法不对,catch ie8关键字
    https://github.com/RubyLouvre/mmRequest/blob/master/dist/mmRequest.js#L690

  • avalon2.2.7 1114 行报错 无法设置未定义或 null 引用的属性“arraybuffer”

早期mmRequest返回的AJAX对象的实现

   require("avalon,mmDeferred", function(avalon, Deferred) {
                    var jqHXR = {
                    }
                    "success,error,complete".replace(avalon.rword, function(method) {
                        jqHXR[method + "Callbacks"] = []
                        jqHXR[method] = function(fn) {
                            this[method + "Callbacks"].push(fn)
                            return this
                        }
                    })

                    var dfd = Deferred(function(promise) {
                        avalon.mix(promise, jqHXR)
                        var then = promise.then
                        promise.then = function(fn1, fn2, fn3) {
                            promise.success(fn1)
                            promise.error(fn2)
                            return then(_, _, fn3)
                        }
                    })
                    dfd.resolveWith = function(context, args, fn) {
                        var array = this.promise.successCallbacks
                        while (fn = array.shift()) {
                            fn.apply(context, args)
                        }
                    }
                    dfd.rejectWith = function(context, args, fn) {
                        var array = this.promise.errorCallbacks
                        while (fn = array.shift()) {
                            fn.apply(context, args)
                        }
                    }
                    dfd.fireWith = function(context, args, fn) {
                        var array = this.promise.completeCallbacks
                        while (fn = array.shift()) {
                            fn.apply(context, args)
                        }
                    }
                    dfd.promise.success(function() {
                        console.log("111111111")
                    }).success(function() {
                        console.log("222222222")
                    }).success(function() {
                        console.log("333333333")
                    })

                })
            })

IE7 下 mmRequest 加载失败

当前 html 页面 url 为 http://127.0.0.1/aaa/bbb/post.htm,html 文件和 js 文件同级目录。
页面以路径 ./mmRequest 加载 mmRequest,代码如下:

require(["./mmRequest"], function(){
    // do something...
});

在 IE7 下会去加载 http://127.0.0.1/mmRequest.js,因此报404,显示 mmRequest 加载失败。
如果以路径 'mmRequest' 加载 mmRequest,代码如下:

require(["mmRequest"], function(){
    // do something...
});

则加载成功。

还有,在组件中调用 mmRequest 的正确方式应该是怎么样的?

微信浏览器下不能正确解析response header

服务器端返回Json类型的数据,在微信浏览器里面下面的代码中,data不是对象而是字符串类型:

avalon.ajax({
   url: "/users"
}).then(function(data){
   avalon.log("type of data = " + (typeof data));
});

如果在请求参数中加上dataType:"json"就正常了,但PC上各浏览器包括QQ浏览器都没这个问题。
调试后发现微信浏览器里面的response header是类似这样的:

content-type: application/json;charset=UTF-8

所有的header key名都是全小写的,应该是这个导致的原因。

谷歌浏览器报错 ie is not defined

Google Chrome 51.0.2704.106 (正式版本) (64 位)

这个版本version 0.41 by 司徒正美

image

引入mmRequest.modern.js就不会报错,
引入mmRequest.js就报错

avalon.serialize出来的form为空字符串,而jQuery的serialize出来的结果是对的

html

<form ms-controller='article_form' ms-on-submit='articleAction'>
  <input type="hidden" ms-duplex='id'>
  <label for="title">title</label>
  <input type="text" id='title' name='title' ms-duplex='title'>
  <br>
  <label for="content">content</label>
  <textarea id="content" name='content' cols="60" rows="10" ms-duplex='content'></textarea>
  <br>
  <button>submit</button>
</form>

js

// ...
  var articleFormModel = avalon.define('article_form', function(vm) {
    vm.id = "";
    vm.title = "";
    vm.content = "";

    vm.articleAction = function(e) {
      avalon.post(vm.id == "" ? '/api/articles' : '/api/articles/' + id, 
                  avalon.serialize(this));
      e.preventDefault();
    };
  });
//...

请问是怎么回事呢?

基于 FormData 方式上传文件失败

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>test</title>
    <script src="avalon.js" type="text/javascript"></script>
    <script>
        var avalonAjax;
        var model = avalon.define("test", function (vm) {
            vm.add = function (e) {
                if (avalonAjax) {
                    var formData = new FormData();
                    var files = this.files;
                    if (files) {
                        console.log(files[0]);
                        formData.append(files[0].name, files[0]);
                        avalon.ajax({
                            data: formData,
                            contentType: "multipart/form-data",
                            url: "/upload",
                            datatype: "text",
                            type: "post"
                        });

//                        var xhr = new XMLHttpRequest();
//                        xhr.onload = function () {
//                            console.log("上传成功!");
//                        };
//                        xhr.open("POST", "/upload", true);
//                        xhr.send(formData);
                    }
                }
                e.preventDefault()
            }
        });

        require(["mmRequest"], function (avalon) {
            avalonAjax = avalon.ajax;
            avalon.log(avalonAjax)
        })

    </script>
</head>
<body>
<form action="/upload" ms-controller="test" ms-on-submit="ajax">
    <input name="email" type=file ms-on-change='add()'>
    </div>
    <button type="submit">提交</button>
</form>

</body>
</html>

见源码,直接用XMLHttpRequest是可以正确上传的,不知道是bug还是我的用法有误

可以像jquery.ajax一样abort()吗

代码如下:

          var homeAjax = avalon.ajax({....});
          setTimeout(function(){
                if(homeAjax && homeAjax.readyState!==4){
                    homeAjax.abort();
                    alert('首页数据加载超时')
                }
            },1e4)

这样做没有用而且报了一个错:

Unhandled promise rejection 

ajax的跨域问题

请问除了jsonp方式解决跨域问题之外,还有别的方式可以解决吗?mmrequest中有没有提供其他方式解决跨域问题

require(['./mmRequest']) 得到的是avalon? 真不可思议...

作者的示例:

require(["./mmRequest"], function(avalon) {
       avalonAjax = avalon.ajax
       avalon.log(avalonAjax)
 })

不知道作者怎么想的, require竟然得到avalon而不是想要得到的模块request.

还有require(['./mmPromise'])也是得到avalon, 而不是想要的Promise, 我就是被这个坑了, 去看了mmPromise源码后才知道要用avalon.mmPromise.

我希望这样子引用:

require(["./mmPromise"], function(Promise) {
      var promise = new Promise(...);
 });

而不是:

require(["./mmPromise"], function(avalon) {
        var promise = avalon.mmPromise(...);
 })

这样更符合模块化的精神.

Callback arguments of `.then` method should not warp resolved data

avalon.getJSON('https://api.github.com/').then(function(data){
    console.log(data);
});

outputs:

[Object, "OK", msPromise]

instead of:

Object {current_user_url: "https://api.github.com/user", current_user_authorizations_html_url: "https://github.com/settings/connections/applications{/client_id}", authorizations_url: "https://api.github.com/authorizations", code_search_url: "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}", emails_url: "https://api.github.com/user/emails"…}

getJSON异常

399行“return avalon.get(url, data, callback, "jsonp")”中的"jsonp"应该是"json"吧?

ajax async:false

原生的Promise可能会让同步AJAX请求变得不怎么“同步”,因为resolve之后,用then绑定的回调不会像一般的回调那样立即执行,于是就像会让ajax(opts)后面的语句先执行了……

Current implementation cause callback untouched when using with other Promise library

Like Promise.all(), after 2a2ec37 :

var url1, url2, callback1, callback2;
callback1 = function(){
    return 1;
}
callback2 = function(){
    return 2;
}
Promise.all([avalon.get(url1).then(callback1),avalon.get(url2).then(callback2)]).then(function(data){
    // This is expected to be `[1,2]`, 
    // but it just return [avalon.get(url1), avalon.get(url2)],
    // i.e. not propagate the Promise correctly.
    console.log(data);
});

avalon.getJSON

jQuery的jQuery.getJSON第一个参数如果符合callback=?的模式,会自动将请求类型转换成JSONP格式,参考文档jQuery.getJSON() | jQuery API Documentation

JSONP

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

考虑到可能有从原jQuery Ajax的JSONP迁移而来的脚本,有必要对这个目前不一样的接口约定作出处理。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.