我对ajax方法感到困惑。我是ajax ajaj的新手(异步javascript和json)。任何人都可以帮助我或任何想法如何在javascript中实现ajax,GETajax,POSTajax
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
}); // ajax
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
}); // getajax
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
}); //postajax
答案 0 :(得分:1)
是的,您应该尝试编写自己的ajax函数。 不要从jQuery开始,以var http_request = new XMLHttpRequest();
开头把它放在一个函数中,添加功能...... 这是我的一个版本
<input type="button" onclick="button_click()" value="CLICK">
<div id="data"></div>
<script>
function button_click() {
// example of use
ajax({
success: receiveNextLocations,
url: 'ajax.php'
});
function receiveNextLocations(data) {
document.getElementById('data').innerHTML = data;
}
}
// ajax function that looks a bit like jQuery $.ajax
// minimal code for what I need; not dummy proof, no error handling ...
// feel free to extend this
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.send(options.data || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
</script>