一般js请求web服务uk可以通过 contentType: "application/json"  获取json效果,为了取得更好的效果,可以在服务端强制返回JSON格式

服务端代码(c#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using Newtonsoft.Json;

namespace ajaxjson
{
    /// <summary>
    /// demo 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
   [System.Web.Script.Services.ScriptService]
    public class demo : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public void  Login(string username,string password)
        {
            User u=new User();
            u.name = "demo";
            u.username = username;
            u.password = password;
            u.money = 1.00;
            string json = JsonConvert.SerializeObject(u);
            Context.Response.Write(json);
            Context.Response.End();
        }
        [WebMethod]
        public void GetUser(int id)
        {
            User u = new User();
            u.name = "demo";
            u.username = "ddd";
            u.password = "333";
            u.money = 1.00;
            string json = JsonConvert.SerializeObject(u);
            Context.Response.Write(json);
            Context.Response.End();
        }

        [WebMethod]
        public void GetList()
        {
            List<User> list=new List<User>();
            User u = new User();
            u.name = "demo";
            u.username = "123";
            u.password = "456";
            u.money = 1.00;
            list.Add(u);
            
            u = new User();
            u.name = "demo";
            u.username = "4444";
            u.password = "6666";
            list.Add(u);
            //该处理会导致必须使用json处理
            string json = JsonConvert.SerializeObject(list);
            Context.Response.Write(json);
            Context.Response.End();
        }
    }

    public class User
    {
        public string username { get; set; }
        public string password { get; set; }
        public string name { get; set; }
        public double money { get; set; }
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-23
猜你喜欢
  • 2022-02-20
  • 2021-09-08
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案