1. 程式人生 > >JS:AJAX的實現

JS:AJAX的實現

1. 複習一下AJAX的實現。

2. 程式碼如下

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		
		<script type="text/javascript">
			
			var $x = (function() {
				return {
					ajax: function(obj) {
						if(window.XMLHttpRequest) {
							var req = new window.XMLHttpRequest()
							if(!obj.type)
								obj.type = 'GET'
							try {
								req.open(obj.type, obj.url, obj.async)
								req.onreadystatechange = function() {
									if(req.readyState == 4 && req.status == 200 || req.status == 304)
										obj.success(req.responseText, req.status, req.readyState)
									else
										obj.error(req.responseText, req.status, req.readyState)
								}
								req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
								req.send(getQueryStr(obj.data))
							} catch(e) {
								obj.error(e.message)
							}
						} else {
							console.log('你的瀏覽器不支援.')
						}
						function getQueryStr(obj) {
							var result = ''
							if(typeof obj !== 'object')
								return result
							for(var tmp in obj) {
								if(typeof obj[tmp] !== 'object')
									result += tmp + '=' + obj[tmp] + '&'
								else
									result += getQueryStr(obj[tmp])
							}
							return result
						}
					}
				}
			})()
			
		</script>
		
	</body>
</html>

至此。