Chapter Six:
jQuery and Ayjaks:
Jquery library is very efficient for working with Ajax technology in itself that it will introduce in this chapter.
Before you know what is Ajax?
The following is a brief Ajax Asynchronous JavaScript and XML. The technology for the first time using Xml data was created in JavaScript.
Ajax is a programming language. But the technology to communicate with the server via JavaScript and Dynamic pages are created.
Ayjaks core object called XMLHttpRequest Are.
Briefly: Ayjaks indirect communication and exchange of information with a web server in the background making things happen and the result is only part of the screen so the entire page needs to reload (refresh) is not.
Ayjaks in jquery:
Functions for working with the jquery work with this technology Ayjaks There is very easy. It can exchange data with the server functions as TXT, HTML, XML and JASON done using two methods: GET and POST.
And the resulting information can be obtained from the server in the selected element (selector) to get screened.
We will continue to review these functions:
Function of load:
$ (Selector). Load (url, data, callback)
This file is in the url address and read the result after the full implementation of the selected element (Selector) display.
A simple example:
Suppose you have a file server files and folders loadtxt.txt want by clicking a button to get it on the page:
<html>
<head>
<script type="text/javascript" src="jquery.js"> </ script>
<script type="text/javascript">
$ (Document). Ready (function () {
$ ("Button"). Click (function () {
$ ('# Result'). Load ('files / loadtxt.txt');
});
});
</ Script>
</ Head>
<body>
<button> Click to Load Data </ button>
<div id="result"> </ div>
</ Body>
</ Html>
After running this program on the contents of text files will display in the div tag.
Another load is a function of two arguments. Argument data: When you want a server script language (php or asp or aspx files, etc.) and should be read from the server for processing Dytayy to send the script to do it by this argument.
Callback function argument also is that when fully loaded operation was to be implemented.
Example:
Suppose you have a folder of files on the file server name loadname.php its content is as follows:
<? Php
$ Name = $ _REQUEST ['name'];
echo 'Welcome'. $ name;
>
This program is rated as the data it receives and displays the welcome message.
Write a program that we want the user to enter a name and then click the Text Box button. Be sent to the above file name and the display and display a message after the completion of work:
<html>
<head>
<script type="text/javascript" src="jquery.js"> </ script>
<script type="text/javascript">
$ (Document). Ready (function () {
$ ("Button"). Click (function () {
var inputname = $ ('input # name'). val ();
$ ('# Result'). Load ('files / loadname.php', {name: inputname}, finish_load);
});
});
function finish_load ()
{
alert ('load finish');
}
</ Script>
</ Head>
<body>
Please Enter Your Name:
<input type="text" id="name" />
<button> Click to Load Data </ button>
<dir id="result"> </ dir>
</ Body>
</ Html>
As you see in the above code on the button after the first read by the function val the value in textbox and in the presence of variable inputnum. Then using this value to load the file and send loadname.php end was the response from the server welcome message finish_load display function is executed and the "load finish" will be displayed on the screen.
Note 1: The function val (): This function returns the value of a form element if the value is and the value of the property value Nsbt element selector.
$ (Selector). Val (content);
Note 2: If you want more data to send data to the server and put them into any data} and {comma "," separated from the next data length:
{Var1: value1, var2: value2, var3: value3}
Function $. Ajax (option):
The lowest level is the work function with Ayjaks in jQuery ajax function. To use this function to send all the parameters required by the argument option to the server.
A simple example:
$. Ajax ({
url: 'ajax / test.html',
success: function (data) {
$ ('. Result'). Html (data);
alert ('Load was performed.');
}
});
In this example the file test.html ajax function call from the server and displays the result in the element class.
With this function is more difficult than most other functions that will be introduced. Therefore recommended to use this function only when needed and can be used instead of simple functions.
Function: $. Get and $. Post:
$. Post (url, data, callback, type);
$. Get (url, data, callback, type);
As the names suggest, these two functions of two different methods and a post script to get the url of the server and the result by Tay callback return call.
- url: the address of the server-side script should be run
- Data: data that is sent to the server: {name: value, name: value, ...}
- Callback: The function that the data is called the server was completely loaded.
- Type: type of data from the server, and can specify the value (html, xml, json, jasonp, script, text) is
The only difference between these two functions is the type of data to the server first and second method uses the post method to get. So if you can only read files from the server and send data to the server, you better get use of the function. (Or the load).
(If you do not know about these two methods of teaching programming languages like php or asp server, please).
Example:
The above was written for an ajax function with the function can get below wrote:
$. Get ('ajax / test.html', function (data) {
$ ('. Result'). Html (data);
alert ('Load was performed.');
});
Or another example: In this example, the example that we wrote at the beginning of the season for the load function write the post. In this case, the code will change as follows:
$ (Document). Ready (function () {
$ ("Button"). Click (function () {
var inputname = $ ('input # name'). val ();
$. Post ('files / loadname.php', {name: inputname}, function (Data) {
$ ('# Result'). Html (Data);
finish_load ();
});
});
});
As you can see in the example. Callback function is called with the data after the call is complete loadname.php and the data that functions much the same result by executing the command script is loadname.php html (data) in the element with ID display will result.
Function getScript:
$. GetScript (url, callback)
Function getScript, to invoke and execute a JavaScript file (js) is used.
Ajax function, this function has the following format:
$. Ajax ({
url: url,
dataType: 'script',
success: success
});
Example:
$.getScript("test.js");
This example makes the call and the file is test.js.
$.getScript("http://blog.monavarian.ir/test.js", function(){
alert("Script loaded and executed.");
});
In the above example file called test.js blog.monavarian.ir address and if the call is successful, a message will display.
Tip: You can use this function when you want global variables put in a separate file and then use it in programs.
Function getJSON:
$. GetJSON (url, data, callback);
This function calls the server's file format is Jason.
My braces (briefly about Jason):
Files, Jason, are data files that are stored in a special data format. Jason also has a specific format for such files, xml files are stored.
ساختار هر شی jason به صورت روبرو می باشد :
{string : value , string:value , … }
Value ها میتوانند شامل مقادیر string , object , number , array , true , false , null باشند .
ساختار Array در jason نیز به فرم زیر می باشد :
[item۱,item۲,item۳,…]
هر item نیز خود میتواند شامل مقادیر معرفی شده در بالا باشد .
برای کسب اطلاعات بیشتر به سایت مرجع Jason به آدرس http://www.json.org مراجعه نمایید .
یک مثال کلی با post : در این مثال قصد داریم فرمی را توسط توابع jquery بررسی کرده و سپس توسط تابع post به سرور فرستاده و نتیجه را نمایش دهیم :
برای مثال میخواهیم یک فرم ساده ورود ایجاد نماییم . فایل اسکریپت forms.php بررسی میکند که نام کاربری و کلمه عبور داده شده در لیست کاربران موجود است . در صورتی که موجود باشد مقدار ۱ و در صورتی که موجود نباشد مقدار صفر را بر میگرداند . محتوی این فایل به صورت زیر است :
<?php
//user defind :
$users = array (
'admin' => 'demo',
'test' => 'test',
'user' => 'pass',
);
$username = trim($_POST['username']);
$pass = trim($_POST['password']);
if ( array_search($pass,$users) == $username )
echo '۱′;
else
echo '۰′;
?>
این فایل را در پوشه files ذخیره میکنیم .
در فایل اصلی html :
<!DOCTYPE html PUBLIC "-//W۳C//DTD XHTML ۱.۰ Transitional//EN" "http://www.w۳.org/TR/xhtml۱/DTD/xhtml۱-transitional.dtd">
<html xmlns=”http://www.w۳.org/۱۹۹۹/xhtml”>
<head>
<script src=”jquery.js” type=”text/javascript” ></script>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-۸″ />
<script type=”text/javascript”>
$(document).ready( function (){
$('input').focus( function (){
$('input').removeClass('select');
$( this ).addClass('select');
});
$('form').submit( function (event){
event.preventDefault();
var user = $('input#username').val();
var pass = $('input#pass').val();
if (!user)
{
$('.result').html('please Enter username');
$('input#username').focus();
}
else if (!pass)
{
$('.result').html('please Enter password');
$('input#pass').focus();
}
else
{
$.post('files/forms.php',{username:user,password:pass}, function (data){
if (data == '۱′)
{
$('.result').html('Login Success <br/> welcome '+user);
$('form').hide();
}
else if (data == '۰′)
$('.result').html('username or password is not correct')
else
$('.result').html('can not connect to server')
})
}
return false;
})
})
</script>
<title>Form Validation</title>
<style>
.result {
color : #FF۰۰۰۰ ;
}
.select {
background : #fff ;
border : ۲px solid #۰۰۰۰ff ;
}
</style>
</head>
<body>
<div class=”result” > </div>
<form action=”#” >
<input type=”text” name=”username” id=”username” />
<input type=”password” name=”pass” id=”pass” />
<input type=”submit” value=”Login”/>
</form>
</body>
</html>
همان طور که در کد بالا مشاهده می کنید . در ابتدا هنگام submit فرم بررسی میکند و در صورت خالی بودن فیلدهای username و یا pass پیغام مناسب درج میکند و سپس نشانگر را به فیلد خالی هدایت می کند (focus ) .
در صورتی که username و pass وارد شده باشد . این مقادیر را به فایل forms.php میفرستد و در نتیجه بررسی میکند : در صورتی که نتیجه فرستاده شده از سرور ۱ باشد پیغام خوش آمد نمایش میدهد و فرم را مخفی (hide ) می نماید در غیر این صورت پیغام مناسب را درج می نماید.
دستهها: آموزش Jquery , طراحي وب | ۱ نظر »