ajax请求

jQuery$.ajax仅仅是对XMLHttpRequest进行了一下封装。

GET

jQuery写法:

$.ajax('myservice/username', {
    data: {
        id: 'some-unique-id'
    }
})
.then(
    function success(name) {
        alert('User\'s name is ' + name);
    },

    function fail(data, status) {
        alert('Request failed.  Returned status of ' + status);
    }
);

Native XMLHttpRequest Object:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'myservice/username?id=some-unique-id');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('User\'s name is ' + xhr.responseText);
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();

上述代码在IE7+浏览器工作正常,如果想要运行在IE6的话,那么需要将new XMLHttpRequest()替换为ActiveXObject("MSXML2.XMLHTTP.3.0")

POST

jQuery写法:

var newName = 'John Smith';

$.ajax('myservice/username?' + $.param({id: 'some-unique-id'}), {
    method: 'POST',
    data: {
        name: newName
    }
})
.then(
    function success(name) {
        if (name !== newName) {
            alert('Something went wrong.  Name is now ' + name);
        }
    },

    function fail(data, status) {
        alert('Request failed.  Returned status of ' + status);
    }
);

Native XMLHttpRequest Object:

var newName = 'John Smith',
    xhr = new XMLHttpRequest();

xhr.open('POST', 'myservice/username?id=some-unique-id');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    if (xhr.status === 200 && xhr.responseText !== newName) {
        alert('Something went wrong.  Name is now ' + xhr.responseText);
    }
    else if (xhr.status !== 200) {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send(encodeURI('name=' + newName));

URL Encoding (URL 编码)

$.param({
    key1: 'some value',
    'key 2': 'another value'
});

Web API提供两个有关URL encode的方法:encodeURIencodeURIComponent

function param(object) {
    var encodedString = '';
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
            if (encodedString.length > 0) {
                encodedString += '&';
            }
            encodedString += encodeURI(prop + '=' + object[prop]);
        }
    }
    return encodedString;
}

发送和接受 JSON

jQuery写法:

$.ajax('myservice/user/1234', {
    method: 'PUT',
    contentType: 'application/json',
    processData: false,
    data: JSON.stringify({
        name: 'John Smith',
        age: 34
    })
})
.then(
    function success(userInfo) {
        // userInfo will be a JavaScript object containing properties such as
        // name, age, address, etc
    }
);

Web API:

var xhr = new XMLHttpRequest();
xhr.open('PUT', 'myservice/user/1234');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        var userInfo = JSON.parse(xhr.responseText);
    }
};
xhr.send(JSON.stringify({
    name: 'John Smith',
    age: 34
}));

上述代码将会在IE8+工作良好

上传文件

你应该知道在IE9和低版本的浏览器里面唯一的上传方法是通过<form>里面创建一个<input type="file">jQuery并没有帮助你做了有关上传的所有事情。在现在的一些浏览器上,上传文件通常借助File API。借助于这个API,上传有两种方式:

  • <form enctype="multipart/form-data">
  • 发送一个body包含file数据的请求

给定下面的markup

<input type="file" id="test-input">

jQuery:

首先我们通过让文件作为multipart encoded request的一部分来上传文件:

var file = $('#test-input')[0].files[0],
    formData = new FormData();

formData.append('file', file);

$.ajax('myserver/uploads', {
    method: 'POST',
    contentType: false,
    processData: false,
    data: formData
});

我们也可以通过POST一个含有文件的请求来上传:

var file = $('#test-input')[0].files[0];

$.ajax('myserver/uploads', {
    method: 'POST',
    contentType: file.type,
    processData: false,
    data: file
});

XMLHttpRequest:

作为form的一部分上传:

var formData = new FormData(),
    file = document.getElementById('test-input').files[0],
    xhr = new XMLHttpRequest();

formData.append('file', file);
xhr.open('POST', 'myserver/uploads');
xhr.send(formData);

作为请求的一部分上传:

var file = document.getElementById('test-input').files[0],
    xhr = new XMLHttpRequest();

xhr.open('POST', 'myserver/uploads');
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);

CORS

CORS就是发送跨源ajax请求,这里有一点重要的是通过跨源ajax请求,cookies默认是不会被发送的,你必须设置XMLHttpRequest上的withCredentials变量,让我们看一眼:

$.ajax('http://someotherdomain.com', {
    method: 'POST',
    contentType: 'text/plain',
    data: 'sometext',
    beforeSend: function(xmlHttpRequest) {
        xmlHttpRequest.withCredentials = true;
    }
});

XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://someotherdomain.com');
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('sometext');

IE8或者IE9中进行Cross-origin ajax requests,只能使用IE-proprietaryXDomainRequest

// For cross-origin requests, some simple logic
// to determine if XDomainReqeust is needed.
if (new XMLHttpRequest().withCredentials === undefined) {
    var xdr = new XDomainRequest();
    xdr.open('POST', 'http://someotherdomain.com');
    xdr.send('sometext');
}

JSONP

你应该慎用或者少用JSONP,因为它已经证明了存在一些安全问题,在现代浏览器中,使用CORS绝对是一种更好的路由选择。

JSONP表示JavaScript Object Notation with Padding,这项工作必须由服务器和客户端共同完成:

$.ajax('http://jsonp-aware-endpoint.com/user', {
    jsonp: 'callback',
    dataType: 'jsonp',
    data: {
        id: 123
    }
}).then(function(response) {
    // handle requested data from server
});

不使用 jQuery:

window.myJsonpCallback = function(data) {
    // handle requested data from server
};

var scriptEl = document.createElement('script');
scriptEl.setAttribute('src',
    'http://jsonp-aware-endpoint.com/user?callback=myJsonpCallback&id=123');
document.body.appendChild(scriptEl);

results matching ""

    No results matching ""