2021年6月4日 星期五

Views

API 傳值和回傳

 目的:練習使用json.html和json.aspx發出ajax請求,並使用json.ashx(沒有畫面的api)返回json物件格式


1.json.html語法

<!DOCTYPE html>
    <head >
        <title>JSON</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>                        
    </head>
<body>
    <H5>Hwllo World</H5>

    <script>
    $.ajax({
        url: "json.ashx",
        data: {"id":"0125","name":"Tina"},
        type: "POST",
        dataType: "json",
        success: function(returnData){
            console.log(returnData);
        },
        error: function(xhr, ajaxOptions, thrownError){
            console.log(xhr.status);
            console.log(thrownError);
        }
    });

    </script>
</body>
</html>

$.ajax各屬性代表意思
(1).請求ashx檔案的時候 要把contentType去掉,還有就是
data 格式為 {”key”,”value”};切記 不要再 大括號外面加雙引號,這樣就會在ashx頁面取不到資料而失敗。
(2).
contentType
contentType是網頁要送到Server的資料型態,若沒指定則預設為'application/x-www-form-urlencoded; charset=UTF-8'
dataType
dataType是網頁預期從Server接收的資料型態,若沒指定則jQuery會根據response的MIME type來推定為xml, json, script, html, text。

2.json.aspx語法code behind要有json.aspx.cs就不放上

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Template.aspx.cs" Inherits="Template" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
    <title>Ch2</title>
<title>Bootstrap Navigation Bar</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>                     
</head>

<body >
<h1>This is Empty</h1>

<form runat="server">

</form>


<script>


$.ajax({
    url: "json.ashx",
    data: {"id":"0125","name":"Tina"},
    type: "POST",
    dataType: "json",
    success: function(returnData){
        console.log(returnData);
    },
    error: function(xhr, ajaxOptions, thrownError){
        console.log(xhr.status);
        console.log(thrownError);
    }
});


</script>

</body>
</html>

3.調用json.ashx的API


<%@ WebHandler Language = "C#" Class = "ResponseOds" %>
using System;
using System.Web;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

public class ResponseOds : IHttpHandler
{
	
    public void ProcessRequest (HttpContext context)
    {
        
        string id=context.Request["id"]; //接到前端傳來值
        if(id=="0125") //判斷是0125的值,在將相對應要回傳值丟到前台
        {
            List<Student> lstStuModel = new List<Student>()
            {
                new Student(){ID=1,Name="張飛",Age=250,Sex="男"},
                new Student(){ID=2,Name="潘金蓮",Age=300,Sex="女"}
            };

            //Newtonsoft.Json序列化
            string jsonData = JsonConvert.SerializeObject(lstStuModel);

            context.Response.ContentType = "application/json"; //回傳json格式
            context.Response.Charset = "utf-8";
            context.Response.Write(jsonData);
        }

        
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }



    class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public string Sex { get; set; }
    }

參考資料 (1).(2).(3).

沒有留言:

張貼留言