前端代碼
function sub() {
var par = JSON.stringify({title: "a", info: "ifno", age: 123 });
console.log(par);
$.ajax({
type: "POST",
url: "abc.ashx",
data: par,//數(shù)據介蛉,json字符串
async: false,
contentType: "application/json",
dataType: "json",
success: function(result) {
alert(result);
}
});
}
后臺ashx代碼:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string result;//獲取json字符串
using (var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
context.Response.Write("Hello World");
}
C#提交json post請求代碼:
/// <summary>
/// json請求
/// </summary>
/// <param name="url"></param>
/// <param name="json"></param>
/// <returns></returns>
public static string PostRequestJson(string url, string json)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json; charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes(json);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
string result;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}