<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Simple Ajax Example</title> <meta name="author" content="Rob Larsen"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="_assets/css/style.css" rel="external nofollow" > </head> <body> <div id="main"> <h1>Simple Ajax Example</h1> <p><strong id="activate">Click here</strong> and content will be appended after this paragraph</p> </div> <script src="_assets/js/ajax.js"></script> </body> </html>
/*
Here's a basic Ajax function
*/
var ajax = function( opts ) {
/*
We have an options argument.
In addition, we want to have some smart defaults.
*/
opts = {
//Is it a Get or Post
type: opts.type || "POST",
//What URL are we going to hit?
url: opts.url || "",
//What do we do with the data
onSuccess: opts.onSuccess || function(){},
//what kind of data do we expect?
data: opts.data || "xml"
};
//create a new XMLHttpRequest
var xhr = new XMLHttpRequest();
//Open the connection to the server
xhr.open(opts.type, opts.url, true);
/*
When the ready state changes
fire this function
*/
xhr.onreadystatechange = function(){
//readyState 4 is "done"
if ( xhr.readyState == 4 ) {
/*
do some simple data processing
There are two components to the returned object-
responseXML and responseText.
Depending on what we're doing we'll need one or the other.
*/
switch (opts.data){
case "json":
//json is text
opts.onSuccess(xhr.responseText);
break;
case "xml":
//XML retains the structure/DOM
//It's passed in whole.
opts.onSuccess(xhr.responseXML);
break;
default :
//Everything else will get TXT
opts.onSuccess(xhr.responseText);;
}
}
};
//close the connection
xhr.send(null);
}
//here's our simple function
var ajaxSample = function(e){
//Simple callback adds some text to the page
var callback = function( data ) {
document.getElementById("main").innerHTML +=
"<p>"
+data.getElementsByTagName("data")[0].getAttribute("value")
+"</p>";
}
//And here's our Ajax call
ajax({
type: "GET",
url: "_assets/data/ajax-1.xml",
onSuccess: callback,
data : "xml"
})
//prevent the default action
e.preventDefault();
}
//Wire everything up
document.getElementById("activate").addEventListener("click", ajaxSample, false);
var ajax = function( opts ) {
opts = {
type: opts.type || "POST",
url: opts.url || "",
onSuccess: opts.onSuccess || function(){},
data: opts.data || "xml"
};
/*
Support for the original ActiveX object in older versions of Internet Explorer
This works all the way back to IE5.
*/
if ( typeof XMLHttpRequest == "undefined" ) {
XMLHttpRequest = function () {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch (e) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch (e) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {}
throw new Error("No XMLHttpRequest.");
};
}
var xhr = new XMLHttpRequest();
xhr.open(opts.type, opts.url, true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
switch (opts.data){
case "json":
opts.onSuccess(xhr.responseText);
break;
case "xml":
opts.onSuccess(xhr.responseXML);
break;
default :
opts.onSuccess(xhr.responseText);;
}
}
};
xhr.send(null);
}
var ajaxSample = function(e){
var callback = function( data ) {
document.getElementById("main").innerHTML += "<p>"
+data.getElementsByTagName("data")[0].getAttribute("value")
+"</p>";
}
ajax({
type: "GET",
url: "_assets/data/ajax-1.xml",
onSuccess: callback,
data: "xml"
})
e.preventDefault();
}
document.getElementById("activate").addEventListener("click", ajaxSample, false);
var ajax = function( opts ) {
opts = {
type: opts.type || "POST",
url: opts.url || "",
onSuccess: opts.onSuccess || function(){},
data: opts.data || "xml"
};
var xhr = new XMLHttpRequest();
xhr.open(opts.type, opts.url, true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
switch (opt.sdata){
case "json":
opt.onSuccess(xhr.responseText);
break;
case "xml":
opt.onSuccess(xhr.responseXML);
break;
default :
opt.onSuccess(xhr.responseText);;
}
}
};
xhr.send(null);
}
var jsonSample = function(e){
var callback = function( data ) {
//here, the data is actually a string
//we use JSON.parse to turn it into an object
data = JSON.parse(data);
/*
we can then use regular JavaScript object references
to get at our data.
*/
document.getElementById("main").innerHTML += "<p>"
+ data.sample.txt
+"</p>";
}
ajax({
type: "GET",
url: "_assets/data/json-1.json",
onSuccess: callback,
data : "json"
})
e.preventDefault();
}
document.getElementById("activate").addEventListener("click", jsonSample, false);
var callback = function( data ) {
document.getElementById("main").innerHTML += "<p>"+ data.sample.txt +"</p>";
}
var jsonpSample = function(e){
//create a script element
var jsonp = document.createElement("script");
//give it a source with the callback name appended in the query string
jsonp.src= "_assets/data/jsonp.do?callback=callback";
//add it to the doc
document.body.appendChild(jsonp);
e.preventDefault();
}
//wire up the event
document.getElementById("activate").addEventListener("click", jsonpSample, false);
/*
callback is a simple function that will be run
when the data is returned from the server
*/
var callback = function( data ) {
/*
it just adds a little bit of text to the document
data is the JSON object returned by the server.
*/
$("#main").append($("<p />").text(data.sample.txt));
}
/*
Wire up the ajax call to this click event
*/
$("#activate").click(
function(){
//call $.ajax with a configuration object
$.ajax({
//it's just a get request
type: 'get',
//we're looking for this URL
url: '_assets/data/json-1.json',
//Our cool callback function
success: callback,
//it's going to be JSON
dataType: "json"
})
}
)
/*
this is the object we're going to post
*/
var myMessages = {
positive : "Today is a good day",
negative : "Today stinks",
meh : "meh"
}
var callback = function( data ) {
$("#main").append($("<p />").text(data.positive));
}
/*
Setting up a simple error handler.
It doesn't do much.
It's just nice to illustrate error handling.
*/
var errorHandler = function( xhr, textStatus, errorThrown ){
throw new Error("There was an error. The error status was " + textStatus );
}
/*
Here's where the action happens.
Attach an event to out simple button.
*/
$("#activate").click(
function(){
//call $.ajax with a configuration object
$.ajax({
//we're sending data to the server
type: 'POST',
//this is our URL
url: '_assets/data/post-responder.do',
/*
This is our data, JSON stringified
jQuery expects to use native JSON
or JSON2.js in unsupported browsers
*/
data: JSON.stringify(myMessages),
//Here's where we set up our callback function
success: callback,
//The data expected from the server
dataType: "json",
//And our simple error handler
error : errorHandler
}
)
}
);
var callback = function( data ) {
//note the document.getelementById alias
dojo.byId("main").innerHTML += "<p>"+ data.sample.txt +"</p>";
}
var getData = function(){
//xhrGet is for get requests
dojo.xhrGet({
//the URL of the request
url: "_assets/data/json-1.json",
//Handle the result as JSON data
handleAs: "json",
//The success handler
load: callback
});
}
// Use connect to attach events
dojo.connect( dojo.byId("activate"), "onclick", getData );
var myMessages = {
positive : "Today is a good day",
negative : "Today stinks",
meh : "meh"
}
var callback = function( data ) {
dojo.byId("main").innerHTML += "<p>"+ data.positive +"</p>";
}
var errorHandler = function(){
throw new Error("We dun goofed.")
}
var postData = function(){
//not surprisingly xhrPost is for POST
dojo.xhrPost({
// The URL of the request
url: "_assets/data/post-responder.do",
//This will be JSON
handleAs: "json",
//Set the headers properly
headers: { "Content-Type": "application/json; charset=uft-8"},
//Use Dojo's JSON utility
postData: dojo.toJson(myMessages),
// The success handler
load: callback,
// The error handler
error: errorHandler
});
}
// Use connect to attach events
dojo.connect( dojo.byId("activate"), "onclick", postData );
// Create a new YUI instance and populate it with the required modules.
YUI().use('node','event', 'json', 'io', function (Y) {
var callback = function( id, xhr ) {
var data = Y.JSON.parse(xhr.responseText);
Y.one('#main').append("<p>"
+ data.sample.txt
+"</p>");
}
Y.one("#activate").on('click',
function(){
Y.io( '_assets/data/json-1.json', {
//This is actually the default
method: 'get',
on: {success: callback}
})
}
)
});
YUI().use('node','event', 'json', 'io', function (Y) {
var myMessages = {
positive : "Today is a good day",
negative : "Today stinks",
meh : "meh"
}
var callback = function( id, xhr ) {
var data = Y.JSON.parse(xhr.responseText);
Y.one('#main').append("<p>"
+ data.positive
+"</p>");
}
var errorHandler = function( id, xhr){
throw new Error("There was an error. The error status was "
+ xhr.statusText
+".")
}
Y.one("#activate").on('click',
function(){
Y.io( '_assets/data/post-responder.do', {
method: 'post',
//Use the Y.JSON utility to convert messages to a string
data : Y.JSON.stringify(myMessages),
//All response methods are encapsulated in
//the on object
on: {success: callback,
failure: errorHandler }
})
}
)
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有