JQuery Ajax 在asp.net中使用总结
https://www.cnblogs.com/acles/articles/2385648.html
补充其他:
Context.Response.ContentType = "text/plain"; //这种方式转中文
Context.Response.Write(jss.Serialize(fruitlist)); //用这种方式将对象转成json 并以字符串返回,用Newtonjson也可以
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.Services;
//using Newtonsoft;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace WebApplication1
{
/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
// [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
//ResponseFormat:方法要返回的类型,一般为Json或者XML
//UseHttpGet:true表示前台的ajax是通过“Get”可以访问此方法,如果前台ajax通过POST,则报错
//false表示前台的ajax是通过"post"来访问此方法,如果前台ajax通过get,则报错
[WebMethod]
public void HelloWorld(string TYPE)
{
if (TYPE=="111")
{
List<fruit> fruitlist = new List<fruit>();
fruit fuit1 = new fruit();
fuit1.id = 1;
fuit1.name = "百果园";
fruitlist.Add(fuit1);
fruit fuit2 = new fruit();
fuit2.id = 2;
fuit2.name = "千果园";
fruitlist.Add(fuit2);
// string json = JsonConvert.SerializeObject(fruitlist);
//return 返回的是xml格式
//return "navList:[{id:1,name:'百果园'},{id: 2,name: '千果园'}]";
//Context.Response.Charset = "GB2312"; //设置字符集类型
//Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
JavaScriptSerializer jss = new JavaScriptSerializer();
Context.Response.ContentType = "text/plain";
Context.Response.Write(jss.Serialize(fruitlist));
Context.Response.End();
}
else
{
//Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Context.Response.Write("error");
Context.Response.End();
}
}
}
}
小程序中调用webservice数据:
getData() {
var that = this
// 商品详情
wx.request({
url: 'http://localhost:81/WebService1.asmx/HelloWorld?TYPE=111',
method: 'GET',
data: {},
header: {
//设置参数内容类型为x-www-form-urlencoded
'content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
success: function (res) {
that.setData({
navList: res.data
})
},
fail: function (err) {
xmdmTotal=0;
},//请求失败
complete: function () {
}//请求完成后执行的函数
})
},
newtonjson使用:
1、添加引用 Newtonsoft.json.dll
2、using Newtonsoft.Json;
3、 string json1 = JsonConvert.SerializeObject(fruitlist);
小程序的问题:
1、如何将小程序 wx.request 调用success结果传递出去:
用this?回调函数中不能用this,在外面定义
var that = this
然后 that.自定义的方法,将结果当做参数传出去自定义函数中使用