ajax在php中应用实例

本文通过具体示例介绍了Ajax的各种形式(如$.ajax()、$.get()、$.post()等)及其在用户登录验证中的应用,并展示了如何利用JSONP实现Ajax跨域数据获取。

1,ajax分为$.ajax(),$.get(),$.post(),$.getJSON() 几种形式,实例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<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

1
2
3
4
5
6
7
8
<?php
$username $_GET['user'];
$password $_GET['password'];
$ret "fail";
if($username == 'zhangsan' && $password == '123'){
    $ret "success";
}
echo json_encode($ret);

test5.php

1
2
3
4
5
6
7
8
<?php
$username $_POST['user'];
$password $_POST['password'];
$ret "fail";
if($username == 'zhangsan' && $password == '123'){
    $ret "success";
}
echo json_encode($ret);

2,ajax跨域获取数据,使用到jsonp,实例如下:

1
2
3
4
5
$.getJSON("http://www.ganji.com/test6.php?callback=?", $("input").serialize() , function(data){
   if(data){
       console.log(data);
   }
});

test6.php

1
2
3
4
5
6
7
8
9
$str 'OK';
$callback $_GET('callback');
    if (!empty($callback)) {
        header("content-type: application/x-javascript; charset=UTF-8");
        echo $callback '(' $str ')';
    else {
        echo $str;
    }
}     
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值