ajax在php中应用实例

Posted 小白驴来也

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax在php中应用实例相关的知识,希望对你有一定的参考价值。

1,ajax分为$.ajax(),$.get(),$.post(),$.getJSON() 几种形式,实例如下:
<html><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><script type="application/javascript" src="../js/jquery-1.7.2.js"></script><script type="application/javascript">$(document).ready(function(){ $("#ajaxBut").click(function(){ $.ajax({ 'type':'get', 'url':'test4.php', 'dateType':'json', 'data':$("input").serialize(), 'success':function(ret){ alert(ret); } });  }); $("#getBut").click(function(){ $.get("test4.php",$("input").serialize(),function(ret){ alert(ret); }); }); $("#postBut").click(function(){ $.post("test5.php",$("input").serialize(),function(ret){ alert(ret); }); }); $("#jsonBut").click(function(){ $.getJSON("test4.php",$("input").serialize(),function(ret){ alert(ret); }); }); });</script><body><form> <h1>user Login</h1> username:<input type="text" name="user" id="user" /><br/> password:<input type="password" name="password" id="password"/><br/> <input type="button" name="but" id = "ajaxBut" value="ajaxLogin" /> <input type="button" name="but" id = "postBut" value="postLogin" /> <input type="button" name="but" id = "getBut" value="getLogin" /> <input type="button" name="but" id = "jsonBut" value="jsonLogin" /></form></body></html>
test4.php
<?php$username = $_GET['user'];$password = $_GET['password'];$ret = "fail";if($username == 'zhangsan' && $password == '123'){ $ret = "success";}echo json_encode($ret);
test5.php
<?php$username = $_POST['user'];$password = $_POST['password'];$ret = "fail";if($username == 'zhangsan' && $password == '123'){ $ret = "success";}echo json_encode($ret);
2,ajax跨域获取数据,使用到jsonp,实例如下:
$.getJSON("http://www.ganji.com/test6.php?callback=?", $("input").serialize() , function(data){ if(data){ console.log(data); }});
test6.php
$str = 'OK';$callback = $_GET('callback'); if (!empty($callback)) { header("content-type: application/x-javascript; charset=UTF-8"); echo $callback . '(' . $str . ')'; } else { echo $str; }}


以上是关于ajax在php中应用实例的主要内容,如果未能解决你的问题,请参考以下文章

ajax在php中应用实例

AJAX相关JS代码片段和部分浏览器模型

JavaScript-Runoob-AJAX:ASP/PHP 实例

PHP 实例 - AJAX 投票

PHP - AJAX 与 PHP

Query实例的ajax应用之二级联动的后台是采用php来做的