實現基本的Ajax和Json請求

來源:互聯網
上載者:User

標籤:

  前面已經封裝好了一個方法ajax(),通過這個方法可以實現Ajax請求,接下來就是給出

常式來測試這個方法和實現簡單的功能。

  視圖的部分代碼如下:

<body>    <div>        the Numger is :                <br /><label id="number">  </label>  <br />        the Students‘ Infomation:<br /><label id="studentInfo">   </label>  <br />        <input type="button" value="請求數字(ajax請求)" onclick=‘requestNumber()‘/>          <label>  </label>        <input type="button" value="請求學生資訊(json請求)" onclick="requestStudentInfo()" />    </div></body>

 

功能一:瀏覽器向伺服器請求一個數字(通過ajax實現)

視圖代碼中添加指令碼代碼:

 1 <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> 2 <script src="../../Scripts/ajax.js" type="text/javascript"></script> 3 <script src="../../Scripts/common.js" type="text/javascript"></script> 4      5 <script language="javascript" type="text/javascript">           6    //請求數字 7   function requestNumber() { 8        ajax("POST","/Home/Get_Number", function (resText) { 9           //直接接收Ajax請求返回的內容10           var text = resText;11           $("number").innerHTML = text;12        });13   }14 </script>

 後台伺服器代碼:

1 //ajax請求的action方法2 public void Get_Number()3 {4     int num =10;5     Response.Write(num);6     return;7 }

 

功能二:瀏覽器向伺服器請求一個學生的資訊(通過Json實現)

視圖代碼中添加指令碼代碼:

 1 //請求學生資訊 2 function requestStudentInfo() { 3     ajax("POST","/Home/Get_Student", function (resText) { 4         //將序列化的字串內容進行解析,得到Js對象 5         var student = JSON.parse(resText); 6         var text=""; 7         text += "學號:" + student.StuId  + "<br />"; 8         text += "姓名:" + student.Name   + "<br />"; 9         text += "性別:" + student.Gender + "<br />";10         text += "年齡:" + student.Age    + "<br />"11 12         $("studentInfo").innerHTML = text;13     });14 }

  代碼中使用到了一個方法JSON.parse(),該方法是將返回的序列化字串解析成一個對象或者對象集合,
因此需要添加js庫--json2.js,如下:

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

後台伺服器代碼:

1 //json請求的action方法2 public JsonResult Get_Student()3 {4     Student student = new Student(1001, "張三","男",22);5     return Json(student);  //Json()方法將一個對象或者對象集合進行序列化6 }

 

運行結果:

 

 

總結:通過封裝好的ajax()方法實現了向伺服器請求一個數字和一個學生資訊對象的功能,

ajax請求和json請求沒有本質上的區別,兩者都是通過ajax()方法來發送XMLHttpRequest

請求,只是ajax請求就直接接收返回的資料就可以了,而json請求需要將接收到的序列化字

符串解析成JS對象或者對象集合(還原序列化),同時也要求伺服器端將對象或者對象集合序列化

成字串進行發送(序列化)。

       

 

實現基本的Ajax和Json請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.