json和jsonp的读取数据区别

数据库data.php

<?php
//$jsonp = $_REQUEST["callback"];

$salam[0]['id']="1";
$salam[0]['name']="salam";
$salam[0]['age']="18";

$salam[1]['id']="2";
$salam[1]['name']="imran";
$salam[1]['age']="30"; 

$result = json_encode($salam);
//$str = $jsonp . "(" .$result.")";
echo $result;
?>

json解析数据json.html

<script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript">
    $(document).ready(function(){ 
     var url="data.php";
     var data={};
     $.getJSON(url,data,function(res){
       //$("#remote").val(res);
       for (var i = 0; i < res.length; i++) {
       $("#remote").append("<li>"+ res[i].age + res[i].name+"</li>");
        }
     })
     
       });

</script>
     </head>
  <body>
<h2 id="con"></H2>
<div id="remote"></div> 
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
</body>

</html>

jsonp解析数据jsonp.html

<script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript">
     jQuery(document).ready(function(){ 
        $.ajax({
             type: "get",
             async: false,
             url: "datap.php",
             dataType: "jsonp",
             jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"feedBackState",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名 
             success: function(data){
                 var $ul = $("<ul></ul>");
                 $.each(data,function(i,v){
                     $("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
                 });
                 $("#remote").append($ul);
             },
             error: function(){
                 alert('fail');
             }
         });
     });
     </script>
     </head>
  <body>
  jsonp 代码:<br/>
  <div id="remote"></div> 
  </body>

 

posted @ 2016-10-12 11:18  salmaq  阅读(861)  评论(0编辑  收藏  举报