$.ajax与$.getJson的区别

来源:互联网 发布:论坛群发软件哪个好 编辑:程序博客网 时间:2024/06/07 13:35


Jquery 中的$.ajax与$.getJSON方法差异发现:

用$ajax方法,需解析Json字符串,

 $.getJSON方法需解析JSON对象。

js代码如下:

[javascript] view plain copy
 print?
  1. function showResult(str){  
  2.     if (str.length == 0) {  
  3.         $("#livesearch").innerHTML = "";  
  4.         $("#livesearch").style.border = "0px";  
  5.         return;  
  6.     }  
  7.       
  8.     $.ajax({  
  9.         url: "livesearch.php",  
  10.         type: "GET",  
  11.         data: "q=" + str,  
  12.         datatype: "JSON",  
  13.         success: function(result){  
  14.             jsonresult = eval("(" + result + ")");  
  15.             strlink = "";  
  16.             $.each(jsonresult, function(i, item){  
  17.                 strlink += "<a href='" + item.linkurl + "'>" + item.linktitle + "</a><br/>";  
  18.             });  
  19.             document.getElementById("livesearch").innerHTML = result;  
  20.             document.getElementById("livesearch").style.border = "1px solid #A5ACB2";  
  21.         }  
  22.     });  
  23.       
  24. //    $.getJSON("livesearch.php", {  
  25. //        q: str  
  26. //    }, function(result){  
  27. //        strlink = "";  
  28. //        $.each(result, function(i, item){  
  29. //            strlink += "<a href='" + item.linkurl + "'>" + item.linktitle + "</a><br/>";  
  30. //        });  
  31. //        document.getElementById("livesearch").innerHTML = strlink;  
  32. //        document.getElementById("livesearch").style.border = "1px solid #A5ACB2";  
  33. //    });      
  34. }  

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

0 0
原创粉丝点击