前端.aspx
<script>
$(function () {
//設定Session
$("#bt1").click(function () {
$.ajax({
type: "post",
data: "{}",
url: "data_query_json.ashx",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response[0].item);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
});
</script>
<button id="bt1" type="button">Click Me!</button>
後端 data_query_json.ashx.cs
using System.Collections.Generic;
using System.Web;
using Newtonsoft.Json;
public void ProcessRequest(HttpContext context)
{
/*
string num1 = context.Request.Form["month"];//如果是get方式context.Request.QueryString
if (!(string.IsNullOrEmpty(num1) || string.IsNullOrEmpty(num2)))
{
context.Response.Write(num1+num2);}
*/
context.Response.ContentType = "application/json";
context.Response.Charset = "utf-8";
context.Response.Write(GetBufferText());
}
public bool IsReusable
{
get
{
return false;
}
}
private class myList
{
public string month { get; set; }
public string item { get; set; }
public string count { get; set; }
}
public static string GetBufferText()
{
List<myList> myLists = new List<myList>();
myLists.Add(new myList { month = "1", item = "APPLE", count = "100" });
myLists.Add(new myList { month = "1", item = "BANANA", count = "50" });
myLists.Add(new myList { month = "1", item = "PINEAPPLE", count = "60" });
string oStrJson = JsonConvert.SerializeObject(myLists); //使用Newtonsoft的API
//string oStrJson =new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myLists); //使用.net內建
return oStrJson;
}
[另外一種直接從前台呼叫後台]
[前端]
$.ajax({
type: "post",
data: qq,
url: "queryChart.aspx/sayHi?"+Math.random(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
dataset = JSON.parse(decodeURIComponent(atob(response.d)));//atob解base64 UTF-8 中文會亂碼
display_new_chart(dataset);
}
});
[後端]
[WebMethod]
public static string sayHi(string query_string)
{
var base64EncodedBytes = System.Convert.FromBase64String(query_string);
string json = Encoding.UTF8.GetString(base64EncodedBytes);
JObject obj = JObject.Parse(json);
foreach (var pair in obj){Debug.Print(pair.Key +"->"+ pair.Value);}
string strEncode = "我是base64 Encode!";
byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(Uri.EscapeDataString("我是base64")); //中文使用Encoding.UTF8.GetBytes(strEncode) 前端中文解碼會亂碼
return Convert.ToBase64String(toEncodeAsBytes);
}
在前端javascrip encode base64 UTF-8編碼使用atob方式解碼中文換變成亂碼, 需採用 encodeURIComponent('中文字') 或編碼decodeURIComponent('中文字').
原本方式
[後端]
->UTF-8->base64
[前端]
base64 ->decoder atob()
解決中文亂碼的方式
[後端]
->URI->UTF-8->base64
[前端]
base64 ->decoder base64->decoder URI
--------------------------------------------------------------------
MVC Ajax局部更新
MVC使用Ajax.BeginForm進行局部更新, 執行後仍會跳頁面, 無法只對目標ID位置進行局部更新.
1. 使用NuGet安裝套件unobtrusive.ajax
2.引用套件
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
----------------------------------------------------------------------
ajax return a value
var cmdExecute = function (url, formData, success, failure) {
var success = (typeof success !== 'undefined') ? success : {};
var failure = (typeof failure !== 'undefined') ? failure : {};
var result;
$.ajax({
url: url,
type: 'post',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
async: false,
success: function (d) {
//console.log(d);
result=d;
},
error: function (data) {
return "Fail";
}
});
return result;
}