标签:
HTML 部分
文件名:test.html
1 <meta charset="utf-8"> 2 <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script> 3 <script> 4 function jsonpCallback(){ 5 alert(‘jsonpCallback‘); 6 } 7 $(document).ready(function(){ 8 $.ajax({ 9 url: "http://127.0.0.1/jsonp.php", 10 data: {username:"admin", password: "admin"}, 11 dataType: "jsonp", 12 jsonp: "callback", 13 success: function(data){ 14 alert(JSON.stringify(data)); 15 }, 16 error:function(XHR, textStatus, errorThrown){ 17 alert(‘error: ‘ + errorThrown); 18 } 19 }); 20 }); 21 </script>
服务器部分
jsonp.php
1 <?php 2 if (!empty($_SERVER[‘HTTPS‘]) && (‘on‘ == $_SERVER[‘HTTPS‘])) { 3 $uri = ‘https://‘; 4 } else { 5 $uri = ‘http://‘; 6 } 7 $uri .= $_SERVER[‘HTTP_HOST‘].$_SERVER[‘REQUEST_URI‘]; 8 9 //获取jsonp回调函数的函数名,即url中callback=后面的值 10 $jsonp_callback = $_GET[‘callback‘]; 11 if($_GET[‘username‘] == ‘admin‘ && $_GET[‘password‘] == ‘admin‘){ 12 $data = array(‘msg‘=>‘登录成功‘); 13 }else{ 14 $data = array(‘msg‘=>‘用户名或密码错误‘); 15 } 16 $json = json_encode($data); 17 //返回jsonp的回调函数名和参数 18 echo $jsonp_callback.‘(‘.$json.‘)‘;
标签:
原文地址:http://www.cnblogs.com/maxuebing/p/4950254.html