<title>jquery Ajax Example Demo </title>
<script language= "javascript" src= ". /lib/jquery.js "></script>
<script language= "JavaScript" >
$ (document). Ready (function ()
{
$ (' #send_ajax '). Click (function () {
var params=$ (' input '). Serialize (); Serialize the value of the form
$.ajax ({
url: ' Ajax_ Json.php ' ,//spooler
type: ' Post ', //Data sending method
dataType: ' JSON ', // Accept data Format
data:params, // The data to be passed
success:update_page//callback function (here is the name of the function)
});
});
//$.post () mode:
$ (' #test_post '). Click (function () {
$.post (
' ajax_json.php ',
{
username:$ (' #input1 '). Val (),
age:$ (' #input2 '). Val (),
sex:$ (' #input3 '). Val (),
job:$ (' #input4 '). Val ()
},
function (data)//callback function
{
var myjson= ';
eval (' myjson= ' + data + '; ');
$ (' #result '). HTML ("Name:" + myjson.username + "<br/> work:" + myjson[ ' Job ']);
}
);
});
//$.get () mode:
$ (' #test_get '). Click (function ()
{
$.get (
' ajax_json.php ',
{
username:$ ("#input1"). Val (),
age:$ ("#input2"). Val (),
sex:$ ("#input3"). Val (),
job:$ ("#input4"). Val ()
},
function (data)//callback function
{
var myjson= ';
eval ("myjson=" + Data + ";");
$ ("#result"). HTML (myjson.job);
}
);
});
});
Function Update_page (JSON)//callback function entity with parameter Xmlhttprequest.responsetext
{
var str= "Name:" +json.username+ "<br /> ";
str+= "Age:" +json.age+ "<br/>";
str+= "Gender:" +json.sex+ "<br/>";
str+= "work:" +json.job+ "<br/>";
str+= "Append test:" +json.append;
$ ("#result"). html (str);
}
</script>
<body>
<div id= "Result" style= "background:orange;border:1px solid red;width:300px;height:200px;" ></div>
<form id= "formtest" action= "" method= "POST" >
<p><span> Enter Name: </span><input type= "text" name= "username" id= "input1"/></p>
<p><span> input Age: </span><input type= "text" Name= "ages" id= "Input2"/></p>
<p><span> input Gender: </span><input type= "text" name= "Sex" id= "INPUT3"/></p>
<p><span> input work: </span><input type= "text" name= "job" id= "Input4"/></p>
</form>
<button id= "Send_ajax" > Submit </button>
<button id= "Test_post" >post submit </button>
<button id= "Test_get" >get submit </button>
</body>
PHP file ajax_json.php:
<?php
$arr = $_post; If you are sending data in $.get (), change to $_get. or simply: $_request
$arr = $_request;
$arr [' append '] = ' test string ';
Print_r ($arr);
$myjson = My_json_encode ($arr);
Echo $myjson;
function My_json_encode ($phparr)
{
if (function_exists ("Json_encode"))
{
Return Json_encode ($phparr);
}
Else
{
Require_once ' json/json.class.php ';
$json = new Services_json;
Return $json->encode ($phparr);
}
}