Skip to content

Instantly share code, notes, and snippets.

@objarni
Last active August 29, 2015 14:21
Show Gist options
  • Save objarni/57fbf2e86e037e4ef960 to your computer and use it in GitHub Desktop.
Save objarni/57fbf2e86e037e4ef960 to your computer and use it in GitHub Desktop.
jQuery+Ajax-exempel
<h1>jQuery demo</h1>
<div id="theDiv">
Detta är en liten text.
</div>
<input id="theButton" type="button" value="Klicka mig!" />
<script type="text/javascript">
$(document).ready(function () {
////////////////////////////////////////////////////
// Byta färg på <div> när man klickar på en knapp //
////////////////////////////////////////////////////
$("#theButton").click(function () {
$("#theDiv").css({ background: "blue" });
});
//////////////////////////////
// AJAX $.load(...) exempel //
//////////////////////////////
$("#theDiv").load('text.html');
/////////////////////////////
// AJAX $.get(...) exempel //
/////////////////////////////
function handleResponse(responseResult) {
if (responseResult.toLowerCase().indexOf("yes") >= 0) {
$("#theDiv").css("background", "lightgreen");
}
else {
$("#theDiv").css("background", "red");
}
}
$("#theButton").click(function () {
$.get(
"CheckUsernameAvailable.aspx",
{ "username": usernameField },
handleResponse
);
});
//////////////////////////////
// AJAX $.ajax(...) exempel //
//////////////////////////////
function handleSuccess(json, textStatus, jqXHR) {
if(json.isAvailable) {
$("#theDiv").html("Username available");
}
else {
$("#theDiv").html("That username is not available.");
}
}
function handleError(jqXHR, textStatus, errorThrown) {
$("#theDiv").html("Error checking username: " + textSTatus);
}
$("#theButton").click(function () {
$.ajax({
url: "CheckUsernameAvailable.aspx",
data: { "username": usernameField },
type: "post",
dataType: "json",
timeout: 3000, // = 3 sekunder
success: handleSuccess,
error: handleError
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment