1. function ajax(opt) {
    2. opt = opt || {};
    3. opt.method = opt.method.toUpperCase() || 'POST';
    4. opt.url = opt.url || '';
    5. opt.async = opt.async || true;
    6. opt.data = opt.data || null;
    7. opt.success = opt.success || function() {};
    8. var xmlHttp = null;
    9. if (XMLHttpRequest) {
    10. xmlHttp = new XMLHttpRequest();
    11. } else {
    12. xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
    13. }
    14. var params = [];
    15. for (var key in opt.data) {
    16. params.push(key + ':' + opt.data[key]);
    17. }
    18. var postData = params.join('&');
    19. console.log(postData);
    20. if (opt.method.toUpperCase() === 'POST') {
    21. xmlHttp.open(opt.method, opt.url, opt.async);
    22. //设置请求头
    23. xmlHttp.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
    24. xmlHttp.setRequestHeader('Content-Type', 'application/json');
    25. xmlHttp.setRequestHeader('Cache-Control', 'private');
    26. xmlHttp.send(JSON.stringify(opt.data));
    27. } else if (opt.method.toUpperCase() === 'GET') {
    28. xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
    29. xmlHttp.send(null);
    30. }
    31. xmlHttp.onreadystatechange = function() {
    32. if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
    33. opt.success(xmlHttp.responseText);
    34. }
    35. };
    36. }

    使用

    1. ajax({
    2. method: 'post',
    3. url: 'user-center/app/shop/follow',
    4. data: {
    5. access_token: 12312,
    6. shop_id: 123123
    7. },
    8. success: function(response) {
    9. console.log(response);
    10. }
    11. });