获取JSON数据,在jQuery中有一个简单的方法 $.getJSON() 可以实现。
下面引用的是官方API对$.getJSON()的说明:
回调函数中接受三个参数,第一个书返回的数据,第二个是状态,第三个是jQuery的XMLHttpRequest,我们只使用到第一个参数。
$.each()方法接受两个参数,第一个是需要遍历的对象集合(JSON对象集合),第二个是用来遍历的方法,这个方法又接受两个参数,第一个是遍历的index,
下面引用的是官方API对$.getJSON()的说明:
回调函数中接受三个参数,第一个书返回的数据,第二个是状态,第三个是jQuery的XMLHttpRequest,我们只使用到第一个参数。
$.each()是用来在回调函数中解析JSON数据的方法,下面是官方文档:
jQuery.getJSON( url, [data,] [success(data, textStatus, jqXHR)] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, jqXHR)A callback function that is executed if the request succeeds.
$.each()方法接受两个参数,第一个是需要遍历的对象集合(JSON对象集合),第二个是用来遍历的方法,这个方法又接受两个参数,第一个是遍历的index,
第二个是当前遍历的值。
在html中,<input value="Test" type="button" οnclick="alert(\"OK\");" />会出错,正确的代码:<input value="Test" type="button" οnclick="alert("OK");" />
因为\是js的转义,我们需要的是HTML的所以转义字符应该使用HTML的。两个双引号的做法是vbScript的,\"这种做法则是javascript的,而HTML的,则是用"
当在使用Jquery append函数时,append增加的实际上是一段html代码。如:<a data-ajax="false" href="www.baidu.com" rel="external"></a>
$("#more").click(function(){
var id =${board.boardId};
var pageNo = ${pagedTopic.currentPageNo}+i;
jQuery.ajax({
type: 'POST',
contentType: 'application/json',
url: '/vehicle/board/listMoreCityTopics-'+pageNo+'-'+id+'.htm',
dataType: 'json',
success: function(data){
var mode = data.pagedTopic.result;
console.log("success3 :"+mode);
$.each(mode,function(i,topic){
$("#ul_info").append(
'<li> <a data-ajax="false" href="www.baidu.com"'+topic.topicTitle
'</a><</li>'
);
});
console.log("success4:"+JSON.stringify(data.pagedTopic.result));
},
error: function(){
alert("error");
}
});
});
这里使用ajax返回json数据。success: function(data),这里后台返回的数据本身就是json对象可以直接用$.each遍历出来。在$("#ul_info").append的时候,不需要转义,js中当一个字符串中需要双引号时,最外围就改成单引号。