Jquery中的$.ajax与$.getJSON JSON传参的用法对比。

  参照示例:http://www.w3school.com.cn/php/php_ajax_xml.asp 修改完成,之前php ajax的例子是采用传统的ajax方式,返回字符串实现。

  本例经过修改,采用JQuery Json方式实现。

 php中增加class

 

class Link
{
	public $linktitle;
	public $linkurl;
	public function gettitle()
	{
		return $this->linktitle;
	}
	
	public function geturl()
	{
		return $this->linkurl;
	}
}


 

输出为json 数组:格式为:[{"linktitle":"sina","linkurl":"http:\/\/www.sina.com"},{"linktitle":"baidu","linkurl":"http:\/\/www.baidu.com"},{"linktitle":"yahoo","linkurl":"http:\/\/www.yahoo.com"},{"linktitle":"amazon","linkurl":"http:\/\/www.amazon.com"}]

//output the json
echo json_encode($arr);

经过对比 Jquery 中的$.ajax与$.getJSON方法差异发现,用$ajax方法,需解析Json字符串,而 $.getJSON方法需解析JSON对象。

js代码如下:

function showResult(str){
    if (str.length == 0) {
        $("#livesearch").innerHTML = "";
        $("#livesearch").style.border = "0px";
        return;
    }
    
    $.ajax({
        url: "livesearch.php",
        type: "GET",
        data: "q=" + str,
        datatype: "JSON",
        success: function(result){
            jsonresult = eval("(" + result + ")");
            strlink = "";
            $.each(jsonresult, function(i, item){
                strlink += "<a href='" + item.linkurl + "'>" + item.linktitle + "</a><br/>";
            });
            document.getElementById("livesearch").innerHTML = result;
            document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
        }
    });
    
//    $.getJSON("livesearch.php", {
//        q: str
//    }, function(result){
//        strlink = "";
//        $.each(result, function(i, item){
//            strlink += "<a href='" + item.linkurl + "'>" + item.linktitle + "</a><br/>";
//        });
//        document.getElementById("livesearch").innerHTML = strlink;
//        document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
//    });    
}

从上看出,两种方法的效果是一样的,区别在于:$ajax 的data参数格式data: "q=" + str,与$.getJSON中的参数格式{q:str}的区别,并且在返回的结果中,$ajax返回的是Json字符串,需用eval方法转化为JSON对象,而$.getJSON返回的是JSON对象,可以直接使用,而$.getJSON的写法也更加简单,推荐使用。

 输出结果:



以上仅为测试,如有谬误,请指正。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值