PHP AJAX JSONP实现跨域请求使用实例

转载自:https://www.cnblogs.com/xcxc/p/3729660.html

实例1

test.html

1

2

3

4

5

6

7

8

9

10

11

12

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>test</title>

<script src="jquery-1.5.2.min.js"></script>

<script src="ajax.js"></script>

</head>

 

<body>

</body>

</html>

 ajax.js

1

2

3

4

5

6

7

8

9

10

11

12

13

$.ajax({

    type : "post",

    url : "ajax.php",

    dataType : "jsonp",

    jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)

    jsonpCallback:"success_jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名

    success : function(json){

        alert('success');

    },

    error:function(){

        alert('fail');

    }

});

 ajax.php

1

2

3

4

5

6

7

8

<?php

 

$data ".......";

$callback $_GET['callback'];

echo $callback.'('.json_encode($data).')';

exit;

 

?>

 jquery-1.5.2.min.js

自己上网下载

当使用jsonp时,使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。


 

实例2

test.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>test</title>

<script src="jquery-1.5.2.min.js"></script>

<script src="ajax.js"></script>

</head>

 

<body>

<form name="form">

<input type="text" name="sex">

<input type="text" name="age">

<input type="button" id="btn" value="button" />

</form>

</body>

</html>

 ajax.js

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

$(document).ready(function(){

 

    $("#btn").click(function(k) {

        //...

        var j = $("form").serializeArray();//序列化name/value

        $.ajax({

            type: 'GET',  //这里用GET

            url: 'ajax.php',

            dataType: 'jsonp',  //类型

            data: j,

            jsonp: 'callback'//jsonp回调参数,必需

            async: false,

            success: function(result) {//返回的json数据

                alert(result.message); //回调输出

                 

                result = result || {};

                if (result.msg=='err'){

                    alert(result.info);

                }else if (result.msg=="ok"){

                    alert('提交成功');

                }else{

                    alert('提交失败');

                }

                 

            },

            timeout: 3000

        })

        //...

    });

     

});

 ajax.php

1

2

3

4

5

6

7

8

<?php

$callback = isset($_GET['callback']) ? trim($_GET['callback']) : ''//jsonp回调参数,必需

$date array("age"=>$_GET['age'], "message"=>$_GET['age']);

$date["msg"]="err";

$date["info"]="因人品问题,发送失败";

$tmp= json_encode($date); //json 数据

echo $callback '(' $tmp .')';  //返回格式,必需

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值