Home  >  Article  >  php教程  >  ThinkPHP中使用ajax接收json数据的方法

ThinkPHP中使用ajax接收json数据的方法

WBOY
WBOYOriginal
2016-06-06 20:15:381287browse

这篇文章主要介绍了ThinkPHP中使用ajax接收json数据的方法,包括了前台js代码与对应的PHP处理代码,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了ThinkPHP中使用ajax接收json数据的方法。分享给大家供大家参考。具体分析如下:

这里通过ThinkPHP+jquery实现ajax,扩展了下,写了个查询,前台代码如下:

首先需要引入jquery.js,主要代码如下:

复制代码 代码如下:

function ajax(id,pic){
    //由于ThinkPHP不解析JavaScript里的ThinkPHP常量,所以需要先在这里定义。
var URL='__URL__';
        $.ajax({
            url: URL+'/returnAjax/id/'+id,//提交访问的URL
            type: 'GET',//提交的方法
            dataType: 'text',//返回的内容的类型,由于PHP文件是直接echo的,那么这里就是text
            timeout: 1000,//超时时间
            error: function(){ //如果出错,,执行函数
                alert('Error loading XML document');
            },
            success: function(data){
                //alert(data);//如果成功,弹出数据
                writeHtml(data,pic);
            }
        });
}
function writeHtml(data,pic){
    var product = eval('(' + data + ')'); //即使不引入json.js也可以转成json对象 
    //alert($("#cate_pic").attr("src"));
    $("#cate_pic").attr("src","../images/"+pic);
    $("#product_pic").attr("src","../Attachments/product/"+product.attachpath+"/"+product.attachthumb);
    $("#product_subject").html(product.subject);
    $("#product_content").html(product.content);
}

Product.class.php中使用echo输出,thinkphp中json_encode()方法可将对象自动转成json格式

复制代码 代码如下:

public function returnAjax(){ 
        $id = $_GET['id']; 
        $Product=D('Product')->where('id='.$id)->find(); 
        //返回一个json格式的数据集 
        echo json_encode($Product); 
//print_r(json_encode($Product)); 
}

返回的数据格式如下:

复制代码 代码如下:

  
{
    "id":"9",
    "userid":"1",
    "cid":"10",
    "cid":"10",
    "subject":"1111",
    "color":"",
    "spec":"",
    "size":"",
    "keywords":"",
    "content":"

1111

",
    "meno":"1111",
    "attachpath":"200903",
    "attachment":"49d1d86e68d31.png",
    "attachthumb":"49d1d86e68d31_thumb.png"
}

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn