参照示例: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的写法也更加简单,推荐使用。
输出结果:
以上仅为测试,如有谬误,请指正。