JSON

Jquery ajax基础教程

字号+ 作者:H5之家 来源:H5之家 2015-11-23 15:57 我要评论( )

这篇文章主要介绍了Jquery ajax基础教程的相关资料,需要的朋友可以参考下

jQuery的Ajax带来了无需刷新的web页面革命。这里就详细介绍一下jQuery所涉及到的Ajax操作。(无需特殊说明,均需要有服务器配置,这里本人用的是Tomcat 7)

1.基于请求加载文件数据

这里的请求通常都是网页的某些操作,如点击等。

而其加载数据的类型归类为以下四种:a.加载HTML文件;b.加载JSON文件;c.加载Javascript文件;d.加载XML文件。

其对应的四种加载方法分别是:load、getJSON、getScript、get。

a.加载HTML文件

把编写好的HTML文件加载到网页中。例如:

//load方法加载html文件

$('#letter-a a').click(function(){

$('#dictionary').load('a.html');

return false;

});

这里a.html也是放在服务器端的一个已经编写好的页面文件,直接调用load,就可以让所匹配的目标内载入HTML内容。

b.加载JSON文件

把编写好的JSON文件加载到网页中。例如:

//加载json文件

$('#letter-b a').click(function(){

$.getJSON('b.json',function(data){

var html = '';

$.each(data,function(entryIndex, entry){

html += "<div>";

html += "<h3>" + entry.term + "</h3>";

html += "<div>" + entry.part + "</div>";

html += "<div>";

html += entry.definition;

if(entry.quote){

html += '<div class="quote">';

$.each(entry.quote, function(lineIndex, line){

html += '<div class="quote-line">' + line + '</div>';

});

if(entry.author){

html += '<div class="quote-author">' + entry.author + '</div>';

}

}

html += "</div>";

html += "</div>";

});

$('#dictionary').html(html);

});

return false;

});

getJSON方法第一个参数是指加载的文件路径,第二个参数是一个加载完成以后的回调函数。通过这个回调函数,就可以对加载好的data进行操作。重复的部分使用each循环处理。最后将拼凑好的html字符串使用html方法加入到目标id=dictionary的元素中。

c.加载Javascript文件

加载Javascript文件和加载HTML文件类似。这里需要注意的是,使用getScript方法加载进来的Javascript会根据当下Javascript环境直接运行。例如:

//执行脚本

$('#letter-c a').click(function(){

$.getScript('c.js');

return false;

});

d.加载XML文件

jQuery中可以使用get方法加载XML文件。例如:

//加载XML文档

$('#letter-d a').click(function(){

$.get('d.xml',function(data){

$('#dictionary').empty();

$(data).find('entry').each(function(){

var $entry = $(this);

var html = '<div class="entry">';

html += '<h3 class="term">' + $entry.attr('term') + '</h3>';

html += '<div class="part">' + $entry.attr('part') + '</div>';

html += '<div class="definition">';

html += $entry.find('definition').text();

var $quote = $entry.find('quote');

if($quote.length)

{

html += '<div class="quote">';

$quote.find('line').each(function(){

html += '<div class="quote-line">';

html += $(this).text() + '</div>';

});

if($quote.attr('author')){

html += '<div class="quote-author">';

html += $quote.attr('author') + '</div>';

}

html += '</div>';

}

html += '</div>';

html += '</div>';

$('#dictionary').append($(html));

});

});

return false;

});

XML文件有一个特点就是,你可以像用jQuery操作HTML那样操作XML的那些元素。如使用attr方法、text方法等等。

2.基于Get方法向服务器获取数据

之前的例子都是从服务器上静态的获取数据文件。而Ajax的价值不只于此,通过get方法从服务器动态的获取数据,为web页面无刷新的实现提供了莫大的帮助。

下面就使用get方法从服务器获取一段所需要的数据。这里,本人结合J2EE的Struts2框架和TOMCAT搭建的服务器端。具体服务器端多种多样,可以是php+apache或者其他什么的都可以。

操作如下,用户点击Eavesdrop则发送get方法到服务器,取得Eavesdrop的数据,并且返回json值,然后在jQuery中装配。

代码如下:

//GET方法加载服务器内容

$('#letter-e a').click(function(){

var requestData = {term:$(this).text().toUpperCase()};

$.get('EGet.action', requestData, function(data){

//返回的数据包结构根据Struts2配置如下:

//{"resultMSG":"{ 内部另一个json结构 }","success":"true"}

//先将返回的数据包拆包

var responseObj = eval("("+data+")");

if(responseObj.success == 'true')

{

$('#dictionary').empty();

//返回成功,接下来再次解包resultMSG

var dataObj = eval("("+responseObj.resultMSG+")");

var html = "";

html += "<div>";

html += "<h3>" + dataObj.term + "</h3>";

html += "<div>" + dataObj.part + "</div>";

html += "<div>";

html += dataObj.definition;

if(dataObj.quote){

html += '<div class="quote">';

$.each(dataObj.quote, function(lineIndex, line){

html += '<div class="quote-line">' + line + '</div>';

});

if(dataObj.author){

html += '<div class="quote-author">' + dataObj.author + '</div>';

}

}

html += "</div>";

html += "</div>";

$('#dictionary').html(html);

}

else

{

var $warning = $('<div>Sorry, your term was not found!</div>');

$('#dictionary').html($warning);

}

});

return false;

});

这里要说明的是由于struts2配置,返回的时候在需要的数据外又打了一层包,用于表示结果内容的resultMSG和是否ajax访问成功的success字段。所以使用了2次eval解包。

这里我后台java程序传递过来的并非配置好的HTML,而是仅仅是json类型的数据,本人认为在java层面编写html并传递不如直接传递数据方便,以后修改样式或者页面结构也都不如直接修改javascript方便。

通过get方法获得服务器数据,相当于向服务器提交如下这种请求:EGet.action?term=XXX

下面放出java后台文件代码:

1.EGet.java

package lhb;

import com.opensymphony.xwork2.ActionSupport;

public class EGet extends ActionSupport

{

private String term;

private Terms sampleTerm;

private String success;

private String resultMSG;

/**

*

*/

private static final long serialVersionUID = 1L;

public String execute() throws Exception

{

initData();

if(term.equals(sampleTerm.getTerm()))

{

success = "true";

resultMSG = "{\"term\": \""+sampleTerm.getTerm()+"\","+

"\"part\": \""+sampleTerm.getPart()+"\","+

"\"definition\": \""+sampleTerm.getDefinition()+"\","+

"\"quote\": ["+

"\"Is public worship, then, a sin,\","+

"\"That for devotions paid to Bacchus\","+

"\"The lictors dare to run us in,\","+

"\"And resolutely thump and whack us?\""+

"],"+

"\"author\": \""+sampleTerm.getAuthor()+"\"}";

}

else{

success = "false";

resultMSG = "fail";

}

return SUCCESS;

}

//初始化数据

private void initData()

{

String partEAVESDROP = "v.i.";

String definitionEAVESDROP = "Secretly to overhear a catalogue of the crimes and vices of another or yourself.";

String quoteEAVESDROP[] = {"A lady with one of her ears applied",

"To an open keyhole heard, inside,",

"Two female gossips in converse free —",

"The subject engaging them was she.",

"\"I think,\" said one, \"and my husband thinks",

"That she's a prying, inquisitive minx!\"",

"As soon as no more of it she could hear",

"The lady, indignant, removed her ear.",

"\"I will not stay,\" she said, with a pout,",

"\"To hear my character lied about!\""};

String authorEAVESDROP = "Gopete Sherany";

Terms EAVESDROP = new Terms();

EAVESDROP.setTerm("EAVESDROP");

EAVESDROP.setPart(partEAVESDROP);

EAVESDROP.setDefinition(definitionEAVESDROP);

EAVESDROP.setQuote(quoteEAVESDROP);

EAVESDROP.setAuthor(authorEAVESDROP);

sampleTerm = EAVESDROP;

}

public String getTerm()

{

return term;

}

public void setTerm(String term)

{

this.term = term;

}

public String getSuccess()

{

return success;

}

public void setSuccess(String success)

{

this.success = success;

}

public String getResultMSG()

{

return resultMSG;

}

public void setResultMSG(String resultMSG)

{

this.resultMSG = resultMSG;

}

}

这个action中的数据本人直接配置了,这里只是做一个示范使用。真正的这些数据在项目中一般是存放在数据库中的。由于这主要是jQuery方面的小示例,就不弄那么麻烦了。

2.Terms.java

package lhb;

public class Terms

{

private String term;

private String part;

private String definition;

private String quote[];

private String author;

public String getTerm()

{

return term;

}

public void setTerm(String term)

{

this.term = term;

}

public String getPart()

{

return part;

}

public void setPart(String part)

{

this.part = part;

}

public String getDefinition()

{

return definition;

}

public void setDefinition(String definition)

{

this.definition = definition;

}

public String[] getQuote()

{

return quote;

}

public void setQuote(String[] quote)

{

this.quote = quote;

}

public String getAuthor()

{

return author;

}

public void setAuthor(String author)

{

this.author = author;

}

}

这个类纯粹就是一个pojo类。没有什么特别的方法。

3.struts.xml

这个是struts2的json方式传递配置

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

"">

<struts>

<!-- 指定全局国际化资源文件 -->

<constant name="struts.custom.i18n.resources" value="i18n"/>

<!-- 指定国际化编码所使用的字符集 -->

<constant name="struts.i18n.encoding" value="GBK"/>

<!-- JSON的action -->

<package name="jsonInfo" extends="json-default">

<action name="EGet" class="lhb.EGet">

<result type="json">

<param name="contentType">text/html</param>

<param name="includeProperties">success, resultMSG</param>

</result>

</action>

</package>

</struts>

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • jquery each遍历json

    jquery each遍历json

    2016-01-31 16:17

  • struts2+ajax+json action向页面返回int型数据,页面报异常org.a

    struts2+ajax+json action向页面返回int型数据,页面报异常org.a

    2016-01-31 15:35

  • jQuery解析json格式数据简单实例

    jQuery解析json格式数据简单实例

    2016-01-26 08:00

  • jQuery+json实现的简易Ajax调用实例

    jQuery+json实现的简易Ajax调用实例

    2016-01-20 18:01

网友点评