初識jQuery的ajax

來源:互聯網
上載者:User

初識jQuery的ajax

 

前面有一篇博文,寫的是ajax請求時,返回json字串和json數組的情境,今天,將原始的ajax修改為jQuery版的ajax。

 

jQuery對ajax做了很多的封裝,使得ajax使用起來非常的方便,省去了很多代碼。

 

閑話少說,直接看代碼吧。

 

代碼

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<script type="text/javascript" src="js/jquery.js"></script>



username
id





Json Array
Username Id

 

背景代碼與前面的相同,這裡不再羅列了,可以參考 ajax響應json字串和json數組。

 

 

代碼講解

 

1 使用jQuery的第一步,便是引入jQuery庫,這裡我將jQuery庫放在了項目根目錄下面的js檔案夾下面。

 


<script type="text/javascript" src="js/jquery.js"></script>

 

2 json字串處理方法

 

 

// json字串處理方法function jsonStr() {$.ajax({url: "jsonStr",dataType: "json",success: function(data) {$("#username").val(data.name);$("#id").val(data.id);}});}

jQuery中,我們無需再去new XMLHttpRequest(),也無需再去關注瀏覽器間的相容問題,這裡jQuery已經幫我們處理好了,位元組使用 $.ajax 就可以了;

 

在回呼函數中,老式的寫法中,需要寫

 

xhr.onreadystatechange = function(data) {if (xhr.readyState == 4 && xhr.status == 200) {

但是 jQuery 的寫法中,一個 success: function(data) { 就可以了,是否簡便了許多呢?

 

 

附上老式的ajax請求代碼

 

function jsonStr() {/** 老式寫法var xhr = new XMLHttpRequest();xhr.open("get", "jsonStr");xhr.onreadystatechange = function(data) {if (xhr.readyState == 4 && xhr.status == 200) {// 將json字串轉換為json對象var obj = eval("(" + data.target.responseText + ")");document.getElementById("username").value = obj.name;document.getElementById("id").value = obj.id;}};xhr.send(null);*/$.ajax({url: "jsonStr",dataType: "json",success: function(data) {$("#username").val(data.name);$("#id").val(data.id);}});}


 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.