日期:2014-05-16  浏览次数:20295 次

jquery与php的json交互2
整理两个现成的函数:json_decode、json_encode
说明:其中json_encode 表示把常用的传统的数据类型如对象、数组、关联数组等转成JSON字符串。其实与JAVA里面的那个工具是一样的。而json_decode刚好相反。
解决需求1.修改
整理两个现成的函数:json_decode、json_encode
说明:其中json_encode 表示把常用的传统的数据类型如对象、数组、关联数组等转成JSON字符串。其实与JAVA里面的那个工具是一样的。而json_decode刚好相反。
解决需求1.修改数据表的时候动态生成一个JSON片段。供JS调用。
服务器端的代码:
function plan2() {
$link = mysql_connect("localhost","root","123") or die("<font color=red>无法建立起来连接。错误信息如下</font>");
mysql_query("SET NAMES gbk");
mysql_select_db("phpcms",$link) or die("<font color=red>在服务器上面无法找到此请确认已建立此DB ");
$result = mysql_query("select id,uuid,uuidtable from dytable ");
$num_rows = @mysql_num_rows($result); //看一下返回多少行记录
if ($num_rows == 0) {
    $b = array();         //这样长度为0 返回的是一个空数组             
}else{         
    while ($row = mysql_fetch_array($result,MYSQL_ASSOC)){
        $b[] = $row;
    }
}
echo json_encode($b);
mysql_close();
}
plan2();

这样生成的JSON是比较方便的了!

2. 客户端如果我们使用JQuery框架的话可以这样处理
<script type="text/javascript">
function ajaxcheck() {
    $.ajax({
        type:"GET",
        url: "http://localhost/PHPCMS/projcode/?number="+Math.random(),
        dataType: 'text',           //注意这里面的格式形式!
        success:function(msg){
           $(eval(msg)).each(function(){
                alert(this.id+" "+this.uuid);//得到值就可以生成多个IMG标签了!
            });
           
        }
    })
}
</script>

如果客户端使用JS的话可以这样处理
<script type="text/javascript">
function ajaxcheck() {
    $.ajax({
        type:"GET",
       url: "http://localhost/PHPCMS/projcode/?number="+Math.random(),
        dataType: 'text',
        success:function(msg){        
            json = eval(msg)
            for(var i=0; i<json.length; i++)
            {
            alert(json[i].id+" " + json[i].uuid)
            }
        }
    })
}
</script>



参考的一个示例代码如下:
客户端代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="../scripts/jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function ajaxcheck() {
    $.ajax({
        type:"GET",