jquery与 ajax 简单例子
jquery与 ajax 简单例子
基于JQuery框架的AJAX
PS:本人这篇始发于PHPCHINA,发现被很多人转了,但却未注明出处,想了一下,还是自己转到这里来。
前几天发了个贴,分享了prototype框架关于AJAX方面的学习过程。然后有人说jquery框架更方便。
正好项目中准备使用thickbox,于是干脆抛弃prototype.js,看起jquery.js了。JQuery确实不错,体积比Prototype小了许多,而且使用起来更方便更灵活。有人说Prototype像JAVA,正统;而JQuery像Ruby,灵活,更趋于OOP。
小试了下AJAX,感觉比prototype简洁多了,在JQuery中,AJAX有三种实现方式:$.ajax(),$.post,$.get()。
XHTML(主要):
代码: 复制内容到剪贴板
<div id="result" style="backgroundrange;border:1px solid red;width:300px;height:400px;"></div>
<form id="formtest" action="" method="post">
<p><span>输入姓名:</span><input type="text" name="username" id="input1" /></p>
<p><span>输入年龄:</span><input type="text" name="age" id="input2" /></p>
<p><span>输入性别:</span><input type="text" name="sex" id="input3" /></p>
<p><span>输入工作:</span><input type="text" name="job" id="input4" /></p>
</form>
<button id="send_ajax">提交</button>
<button id="test_post">OST提交</button>
<button id="test_get">GET提交</button>
JS:
1、引入jquery框架:
代码: 复制内容到剪贴板
<script type="text/javascript" src="../js/jquery.js"></script>
2、构建AJAX,JQUERY的好处是不需要在XHTML中使用JS代码来触发事件了,可以直接封装在JS文件中:
代码: 复制内容到剪贴板
<script type="text/javascript">
//$.ajax()方式
$(document).ready(function (){
$('#send_ajax').click(function (){ //直接把onclick事件写在了JS中,而不需要混在XHTML中了
var params=$('input').serialize(); //序列化表单的值,与prototype中的form.serialize()相同
$.ajax({
url :'ajax_test.php', //后台处理程序
type:'post', //数据发送方式
dataType:'json', //接受数据格式
data:params, //要传递的数据
success:update_page //回传函数(这里是函数名)
});
});
});
function update_page (json) { //回传函数实体,参数为XMLhttpRequest.responseText
var str="姓名:"+json.username+"";
str+="年龄:"+json.age+"";
str+="性别:"+json.sex+"";
str+="工作:"+json.job;
$("#result").html(str);
}
//$.post()方式:
$(function (){//$(document).ready(function (){ 的简写
$('#test_post').click(function (){
$.post('ajax_test.php',
{username('#input1').val(),age('#input2').val(),sex('#input3').val(),job('#input4').val()},
function (data){ //回传函数
var myjson='';
eval('myjson='+data+';');
$('#result').html("姓名:"+myjson.username+"
工作:"+myjson['job']);
});
});
});
$.get()方式:
$(function (){
$('#test_get').click(function (){
$.get('ajax_test.php',
{username("#input1").val(),age("#input2").val(),sex("#input3").val(),job("#input4").val()},
function (data) {
var myjson='';
eval("myjson="+data+";");
$("#result").html(myjson.job);
});
});
});
</script>
PHP代码:
代码: 复制内容到剪贴板
<?php
$arr=$_POST; //若以$.get()方式发送数据,则要改成$_GET.或者干脆_REQUEST
$myjson=json_encode($arr);
echo $myjson;
?>
+----------------------------------------------------------
* @param mixed $where 数据
* @param string $tables 数据表名
* @param string $fields 字段名
* @param string $order 排序
* @param string $limit
* @param string $group
* @param string $having
* @param boolean $cache 是否缓存
* @param boolean $lazy 是否惰性加载
* @param boolean $lock 是否加锁
+----------------------------------------------------------
* @return ArrayObject
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function find($where,$tables,$fields='*',$order=null,$limit=null,$group=null,$having=null,$join=null,$cache=false,$lazy=false,$lock=false)
{
if(in_array($this->getDbType(),array('MSSQL','IBASE'),true) ) {
$this->queryStr = 'SELECT '.$this->parseLimit($limit)
.$this->parseFields($fields)
.' FROM '.$tables
.$this->parseJoin($join)
.$this->parseWhere($where)
.$this->parseGroup($group)
.$this->parseHaving($having)
.$this->parseOrder($order);
}else{
$this->queryStr = 'SELECT '.$this->parseFields($fields)
.' FROM '.$tables
.$this->parseJoin($join)
.$this->parseWhere($where)
.$this->parseGroup($group)
.$this->parseHaving($having)
.$this->parseOrder($order);
if("ORACLE" == $this->getDbType())
if($limit[0] <= 0){
if($limit[1] > 0)
$this->queryStr = "SELECT * FROM (".$this->queryStr.") WHERE ROWNUM <= ".$limit[1];
}else{
$whereClause = "";
if($limit[1] > 0)
$whereClause = " WHERE ROWNUM <= ".($limit[0] + $limit[1]);
$this->queryStr = "SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ("
.$this->queryStr.") ROW_"
.$whereClause
.") WHERE ROWNUM_ > "
.$limit[0];
}
else
$this->queryStr .= $this->parseLimit($limit);
}
return $this->query('',$cache,$lazy,$lock);
}
<?php session_start(); ?>
<?php
{
$authcode = new AuthCode();
if ($authcode->GetUriFileName() == "authcode.php")
{
$authcode->OutputImg();
}
}
function ChkAuthcode($Authcode)
{
if ($_SESSION['AuthCode'] == $Authcode)
{
$rtn = true;
}
else
{
$rtn = false;
}
$_SESSION['AuthCode'] = rand(0, 999999);
return $rtn;
}
class AuthCode
{
/* Public Variables */
/* Private Variables */
var $image;
#
var $sBgcolor;
var $nWidth;
var $nHeight;
var $nLen;
var $bNoise;
var $nNoise;
var $bBorder;
var $aFontlist;
/* Constractor */
function AuthCode()
{
$this->sBgcolor = "#FFCC00";
$this->nWidth = 70;
$this->nHeight = 25;
$this->nLeftMargin = 5;
$this->nRightMargin = 5;
$this->nTopMargin = 3;
$this->nBottomMargin = 2;
$this->nLen = 4;
$this->bNoise = true;
$this->nNoisePoint = 50;
$this->nNoiseLine = 5;
$this->bBorder = true;
$this->aFontlist[0] = "./fonts/arial.ttf";
$this->aFontlist[1] = "./fonts/comic.ttf";
$this->aFontlist[2] = "./fonts/raavi.ttf";
$this->aFontlist[3] = "./fonts/verdanai.ttf";
$this->aFontlist[4] = "./fonts/tahoma.ttf";
$this->aFontlist[5] = "./fonts/shruti.ttf";
$this->aFontlist[6] = "./fonts/BKANT.TTF";
$this->aFontlist[7] = "./fonts/comicbd.ttf";
$this->aFontlist[8] = "./fonts/courbi.ttf";
$this->aFontlist[9] = "./fonts/times.ttf";
}
function OutputImg()
{
$this->image = "";
$this->image = imagecreate($this->nWidth, $this->nHeight);
$back = $this->getcolor($this->sBgcolor);
imagefilledrectangle($this->image, 0, 0, $this->nWidth, $this->nHeight, $back);
$size = ($this->nWidth - $this->nLeftMargin - $this->nRightMargin)/$this->nLen;
if($size>($this->nHeight - $this->nTopMargin - $this->nBottomMargin))
$size=$this->nHeight - $this->nTopMargin - $this->nBottomMargin;
$left = ($this->nWidth-$this->nLen*($size+$size/10))/2 + $this->nLeftMargin;
$code = "";
for ($i=0; $i<$this->nLen; $i++)
{
$randtext = rand(0, 9);
$code .= $randtext;
$textColor = imagecolorallocate($this->image, rand(0, 100), rand(0, 100), rand(0, 100));
$font = $this->aFontlist[rand(0,9)];//rand(1,4).".ttf";
$randsize = rand($size-$size/10, $size+$size/10);
$location = $left+($i*$size+$size/10);
imagettftext($this->image, $randsize, rand(-18,18), $location, rand($size, $size+$size/5) + $this->nTopMargin, $textColor, $font, $randtext);
}
if($this->bNoise == true) $this->setnoise();
$_SESSION['AuthCode'] = $code;
$bordercolor = $this->getcolor(" ");
if($border==true) imagerectangle($this->image, 0, 0, $this->nWidth-1, $this->nHeight-1, $bordercolor);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Cache-Control: private");
header("Pragma: no-cache"); // HTTP/1.0
header("Content-type: image/png");
imagepng($this->image);
imagedestroy($this->image);
return $sAuthcode;
}
function ChkAuthcode($Authcode)
{
if ($this->GetAuthcode() == $Authcode)
{
$rtn = true;
}
else
{
$rtn = false;
}
$_SESSION['AuthCode'] = rand(0, 999999);
return $rtn;
}
function GetAuthcode()
{
$x_AuthCode = $_SESSION['AuthCode'];
$_SESSION['AuthCode'] = rand(0, 999999);
return $x_AuthCode;
}
/* Private Functions */
function GetUriFileName()
{
return substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], '/') + 1 , strlen($_SERVER['SCRIPT_NAME']) - strrpos($_SERVER['SCRIPT_NAME'], '/'));
}
function setnoise()
{
for ($i=0; $i<$this->nNoiseLine; $i++){
$randColor = imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($this->image, rand(0, $this->nWidth), rand(0, $this->nHeight), rand(0, $this->nWidth), rand(0, $this->nHeight), $randColor);
}
for ($i=0; $i<$this->nNoisePoint; $i++){
$randColor = imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($this->image, rand(0, $this->nWidth), rand(0, $this->nHeight), $randColor);
}
}
function getcolor($color)
{
$color = eregi_replace ("^#","",$color);
$r = $color[0].$color[1];
$r = hexdec ($r);
$b = $color[2].$color[3];
$b = hexdec ($b);
$g = $color[4].$color[5];
$g = hexdec ($g);
$color = imagecolorallocate ($this->image, $r, $b, $g);
return $color;
}
}
?>
function backup($bakfile = null, $tables = array())
{
if (empty($bakfile)) {
$bakfile = $this->dbname . date("Ymdhis") . '.sql';
} elseif (is_dir($bakfile)) {
if (preg_match('//$/', $bakfile)) {
$bakfile = $bakfile . $this->dbname . date("Ymdhis") . '.sql';
} else {
$bakfile = $bakfile . '/' . $this->dbname . date("Ymdhis") . '.sql';
}
}
if (!$tables) {
$this->query("SHOW TABLES");
while ($row = mysql_fetch_row($this->queryID)) {
$tables[] = $row[0];
}
} else {
foreach ($tables as $k => $v) {
$tables[$k] = $this->tablePrefix . $v;
}
}
if ($fp = fopen($bakfile, 'wb')) {
if ($this->dbcharset) {
fwrite($fp, "SET NAMES " . $this->dbcharset . ";nn");
}
foreach ($tables as $table) {
$this->dumpTable($table, $fp);
fwrite($fp, "n");
}//foreach
fclose($fp);
return true;
} else {
return false;
}//if
}
//私有方法 导出表格
function dumpTable($fullTableName, $fp)
{
//备份表结构
fwrite($fp, "-- n-- {$fullTableName}n-- n");
$row = $this->findBySql("SHOW CREATE TABLE `{$fullTableName}`");
fwrite($fp, $row['Create Table'] . ";nn" );
//备份表库数据
$this->query("SELECT * FROM `{$fullTableName}`");
while ($row = mysql_fetch_assoc($this->queryID)) {
foreach ($row as $k=>$v) {
$row[$k] = "'" . $this->qstr($v) . "'" ;
}
$sql = "INSERT INTO `$fullTableName` VALUES (" . join(",", $row) . ");n";
fwrite($fp, $sql);
}
mysql_free_result($this->queryID);
fwrite($fp, "n");
}
//恢复数据库文件
function restore($bakfile)
{
if ($fp = fopen($bakfile, 'r')) {
$sql = '';
while (!feof($fp)) {
$line = fgets($fp);
if (strpos($line,'--')!==0)
{
$sql .= $line;
//pp($sql);
}
if (preg_match('/;s*$/', $sql)) {
$this->query($sql);
$sql = '';
}
}
fclose($fp);
return true;
} else {
return false;
}
}
<?php
if (isset($_GET['action']) && $_GET['action']=='update')
{
//update notice data
//上传文件
require_once("upload_class.php");
$f = new Upload( $savepath, $fileFormat, $maxsize, $overwrite);
if (!$f->run('img'))
{//下面的img是Form中上传文件的input的名字
echo $f->errmsg(); //这里只能传递最后一个出错的信息,详细的信息在$f->getInfo()中可以得到。
print_r($f->returnArray);
}
echo "
<script src="".__FILENAME__."/js/jquery.js" type="text/javascript"></script>
<script>
var ptext='';
ptext="OK";
//alert($('#img_view').html());
parent.$('#img_view').html(ptext);
</script>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="{{$tempurl}}/admin.css" rel="stylesheet" type="text/css" />
<link href="{{$baseurl}}/js/calendar/default/datePicker.css" rel="stylesheet" type="text/css" />
<script src="{{$baseurl}}/js/calendar/WdatePicker.js" type="text/javascript"></script>
<script src="{{$baseurl}}/js/jquery.js" type="text/javascript"></script>
<script src="{{$baseurl}}/js/Forms.js" type="text/javascript"></script>
<script src="{{$baseurl}}/js/FormValid.js" type="text/javascript"></script>
<script type="text/javascript">
FormValid.succeed = function () {
$.post("./article.php?action=update",$.getForms("update"),function (msg){
alert(msg);
if(msg=="更新公告成功")
{
location.href("./article.php");
}
//location.href("{{$baseurl}}/index.php");
});
return false;
}
function file_addupload(type)
{
//负责增加图片输入框
var ptext='';
ptext=$("#"+type+"_more").html()+"<br /><input type='file' name='"+type+"[]' class='input' />";
$("#"+type+"_more").html(ptext);
}
</script>
<title>发布文章--编辑页面</title>
</head>
<body >
<table width="99%" border="0" cellpadding="0" cellspacing="1" class="install">
<tr>
<td colspan="2" class="title">编辑文章内容</td>
</tr>
{{section name=article loop=$article}}
<form action="./article.php?action=update" method="post" name="update" enctype="multipart/form-data" target="upload_iframe">
<input type="hidden" name="article_id" value="{{$id}}">
<tr>
<td class="left">文章标题:</td>
<td class="right"><input type="text" id="title" name="article_title" value="{{$article[article].title}}" class="input" size="35" valid="required" errmsg="文章标题不能为空" /></td>
</tr>
<tr>
<td class="left">发布IP:</td>
<td class="right"><input type="text" id="ip" value="{{$article[article].ip}}" name="ip" class="input" readonly /></td>
</tr>
<tr>
<td class="left">作者:</td>
<td class="right"><input type="text" id="author" name="article_validtime" value="{{$article[article].author}}" valid="required" errmsg="请输入文章作者" /></td>
</tr>
<tr>
<td class="left">分类:</td>
<td class="right"><select name='sort'>
{{html_options options=$sort_options selected=$article[article].sort }}
</select></td>
</tr>
<tr>
<td class="left">来源:</td>
<td class="right"><input type="text" id="comes" name="comes" value="{{$article[article].comes}}" class="input"/></td>
</tr>
<tr>
<td class="left">是否置顶:</td>
<td class="right">{{html_radios name='is_top' options=$is_top_radios checked=$article[article].is_top separator=' ' _note='是否置顶|radio|1=>是,0=>否' }}</td>
</tr>
<tr>
<td class="left">内容:</td>
<td class="right">{{$editor}}</td>
</tr>
<tr>
<td class="left">图片上传:</td>
<td class="right">
<span id="img_view">
<input type="file" name="img[]" class="input" />
<a href="#" onclick="file_addupload('img')">++</a>
<span id="img_more"></span>
</span>
</tr>
<tr>
<td class="left">文件上传:</td>
<td class="right"><input type="file" name="file[]" class="input" />
<a href="#" onclick="file_addupload('file')">++</a>
<span id="file_more"></span>
</td>
</tr>
<tr>
<td colspan="2" class="page" style="text-align:center;"><input type="submit" name="submit" class="button" value="保存" /> <input type="button" name="article_return" value="返回" class="button" onclick="javascript:location.href('./article.php');" /></td>
</tr>
</form>
{{/section}}
</table>
<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
</iframe>
</body>
</html>
相关文章
- 这篇文章主要介绍了jquery实现加载更多"转圈圈"效果,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-10
- 最近接了一个项目,其中有需求要用到jquery分页控件,上网也找到了需要分页控件,各种写法各种用法,都是很复杂,最终决定自己动手写一个jquery分页控件,全当是练练手了。写的不好,还请见谅,本分页控件在chrome测试过,其他的兼容性...2015-10-30
- 最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
- 有时我们在页面上需要选择数值范围,如购物时选取价格区间,购买主机时自主选取CPU,内存大小配置等,使用直观的滑块条直接选取想要的数值大小即可,无需手动输入数值,操作简单又方便。HTML首先载入jQuery库文件以及jRange相关...2015-03-15
- 本文实例讲述了jQuery实现非常实用漂亮的select下拉菜单选择效果。分享给大家供大家参考,具体如下:先来看如下运行效果截图:在线演示地址如下:http://demo.jb51.net/js/2015/js-select-chose-style-menu-codes/具体代码如...2015-11-08
- 这篇文章主要为大家详细介绍了jQuery实现广告显示和隐藏动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-07-05
- 本文实例讲述了jquery实现的伪分页效果代码。分享给大家供大家参考,具体如下:这里介绍的jquery伪分页效果,在火狐下表现完美,IE全系列下有些问题,引入了jQuery1.7.2插件,代码里有丰富的注释,相信对学习jQuery有不小的帮助,期...2015-10-30
- 拜读一个开源框架,最想学到的就是设计的思想和实现的技巧。废话不多说,jquery这么多年了分析都写烂了,老早以前就拜读过,不过这几年都是做移动端,一直御用zepto, 最近抽出点时间把jquery又给扫一遍我也不会照本宣科的翻译...2014-05-31
- 这篇文章主要介绍了jQuery事件绑定用法,结合实例形式较为详细的分析了jQuery事件绑定的实现原理与相关注意事项,并附带了相关绑定方法的使用说明,重点介绍了bind和live的区别,需要的朋友可以参考下...2016-01-21
- JQuery使我们在开发Ajax应用程序的时候提高了效率,减少了许多兼容性问题,我们在Ajax项目中,遇到ajax异步获取数据出错怎么办,我们可以通过捕捉error事件来获取出错的信息。在没给大家介绍正文之前先给分享Jquery中AJAX参...2015-11-24
- 这篇文章主要介绍了jQuery获得字体颜色16位码的方法,涉及jQuery样式操作及正则表达式使用技巧,非常简单实用,需要的朋友可以参考下...2016-02-23
- 当页面打开时我们需要执行一些操作,这个时候如果我们选择使用jquery的话,需要重写他的3中方法,自我感觉没什么区 别,看个人喜好了,第二种感觉比较简单明了: 第一种: 复制代码 代码如下: <script type="text/javas...2014-06-07
jquery中常用的SET和GET$(”#msg”).html循环介绍
复制代码 代码如下: $(”#msg”).html(); //返回id为msg的元素节点的html内容。 $(”#msg”).html(”new content“); //将“new content” 作为html串写入id为msg的元素节点内容中,页面显示粗体的new content $(”...2013-10-13jQuery Mobile开发中日期插件Mobiscroll使用说明
这篇文章主要介绍了jQuery Mobile开发中日期插件Mobiscroll使用说明,需要的朋友可以参考下...2016-03-03jQuery 1.9使用$.support替代$.browser的使用方法
jQuery 从 1.9 版开始,移除了 $.browser 和 $.browser.version , 取而代之的是 $.support 。 在更新的 2.0 版本中,将不再支持 IE 6/7/8。 以后,如果用户需要支持 IE 6/7/8,只能使用 jQuery 1.9。 如果要全面支持 IE,并混合...2014-05-31jQuery遍历DOM的父级元素、子级元素和同级元素的方法总结
借助jQuery我们可以轻松地堆DOM元素进行向上、向下遍历以及同级的遍历,本文我们即来整理jQuery遍历DOM的父级元素、子级元素和同级元素的方法总结:...2016-07-25- jquery中jquery.offset().top / left用于获取div距离窗口的距离,jquery.position().top / left 用于获取距离父级div的距离(必须是绝对定位的div)。 (1)先介绍jquery.offset().top / left css: 复制代码 代码如下: *{ mar...2013-10-13
- 有时候我们为了省事就操作键盘组合键去代替使用鼠标,我们今天就使用JQuery实现Ctrl+Enter提交表单。我们发帖时,在内容输入框中输入完内容后,可以点击“提交”按钮来发表内容。可是,如果你够“懒”,你可以不用动鼠标,只需按...2015-10-23
- 在DOM操作中,常常需要动态创建HTML内容,使文档在浏览器里的呈现效果发生变化,并且达到各种各样的人机交互目的....2016-04-27
- 直接为大家介绍制作过程,希望大家可以喜欢。HTML结构该页面切换特效的HTML结构使用一个<main>元素来作为页面的包裹元素,div.cd-cover-layer用于制作页面切换时的遮罩层,div.cd-loading-bar是进行ajax加载时的loading进...2015-10-30