1. 程式人生 > >原生ajax請求和jQuery的ajax請求

原生ajax請求和jQuery的ajax請求

原生ajax請求

var name = document.getElementById('user');
var pwd= document.getElementById('pwd');
var btn= document.getElementById('btn');

btn.onclick = function () {
	var xhr;
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else {
		xhr = new ActiveObject('Microsoft.XMLHTTP');
	}
	var url = 'http://......';
	xhr.open ('post', url);
	xhr.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded');
	xhr.send('memberId=' + name.value + '&password=' + pwd.value);
	xhr.onreadystatechange = function () {
		if (xhr.status === 200 && xhr.readyState === 4)  {
			var data = xhr.responseText;
			var json = JSON.parse(data);
			console.log(json);
		}
	}
}

jQuery的ajax請求

$.ajax({
	url: 'http://.......',
	type: 'post',
	data: { memberId: name.value, password: pwd.value },
	dataType: 'json',
	success: function (resp) {
		console.log(resp) 
	},
	error: function (err) {
		console.log(err)
	}
})