AJAX - 原生js 简单使用 : c#后台
一、 js:-Ajax传递数据到后台C#(原生js)
1.1 Default.aspx
// js
function funCallBack(data) {
alert(data )
}
getAjaxPost("demo1.aspx", "pathUrl=" + path,funCallBack);
//自定义方法: getAjaxPost方法参数(路径,参数1=参赛值1&参数2=参数值2...,回调函数)
function getAjaxPost(url, jsonData, fun) { var result = ""; var xhr = null; if (window.ActiveXObject) { // 以Microsoft IE的方式创建 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else { xhr = new XMLHttpRequest(); } //第二步:对象的open() xhr.open("post", url, true); //POST方式需要自己设置http的请求头 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //第三步: 发送数据, post方式发送数据 xhr.send(jsonData); // 第四步 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { result = xhr.responseText; // alert(xhr.responseText) fun( result ); } } }
1.2 demo1.aspx.cs
c# :响应
demo1.aspx
demo1.aspx.cs
using System; public partial class demo1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string pathUrl = Request["pathUrl"]; // string pathUrl = Request.QueryString["pathUrl"]; Response.ContentType = "application/json"; Response.Write( pathUrl ); Response.End(); } }
二、jq: Ajax传递数据到后台C#(JQ)
2.1 Default.aspx
$("#GridView1 td a[title$=XmlBtn]").click(function () {
// alert(1);
// var td = $(this).parent("td");
// var tds = td.siblings();
// var workNo = tds.eq(1).html();
// var dir = tds.eq(3).html();
// ajax....
})
1 // jq Ajax 2 $.ajax( 3 { type: "post", 4 url: "demo1.aspx?workNo=" + workNo + "&dir=" + dir + "&", 5 success: function (data) { 6 alert(data); 7 return false; 8 }, 9 failure: function () { 10 alert("error"); 11 return false; 12 } 13 });
2.2 demo1.aspx.cs
using System;
using System.Data;
using System.IO;
public partial class demo1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try {
//根据目录和xml报文号拼接xml路径
string workNo = Request["workNo"].ToString(); // string pathUrl = Request.QueryString["pathUrl"];
string dir = Request["dir"].ToString();
if ( workNo == null || workNo == "") { Response.Write("-1:报文号或者路径错误"); }
dir = XmlFileHelper.getXmlBakPath(workNo, dir); ;
dir = XmlFileHelper.checkXmlPath(workNo, dir);
string path = dir;
StreamReader rd = new StreamReader(path);
string content = rd.ReadToEnd();
rd.Close();
this.Response.Write(content);
}
catch (Exception exp)
{
Response.Write("-1:错误。" + exp.ToString());
}
}
}
三、jq: Ajax传递数据到后台C#(JQ,json)(類似:二)
3.1 Default.aspx
function getItemDesc() {
var item_first2Char = $("#<%=txb_CALSS_first2Char.ClientID%>").val();
var item_next2Char = $("#<%=txb_CALSS_next2Char.ClientID%>").val();
if (item_first2Char.length == 2 && item_next2Char.length == 2) {
var data = { "itemOfTopFour": item_first2Char + item_next2Char };
var url = "GetItemDesc.aspx/AjaxMethod"
$.post(url, data, function () { alert("ok!"); alert(data); console.log(data) });
});
3.2 GetItemDesc.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ViewPages_GetItemDesc : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string itemOfTopFour = Request["itemOfTopFour"] == null ? string.Empty : Request["itemOfTopFour"].ToString().Trim();
itemOfTopFour = itemOfTopFour.Replace("'", "");
string sql = string.Format(@" select ITEMOFLASTTWODESC ,itemOfTopFour from {0} where substr( itemOfTOPfOUR , 0,4 ) ='{1}' ", "P50020_PLM_CATEGORY_4", itemOfTopFour);
DataTable DT = App_Code.OracleHelper.Query(sql).Tables[0];
string DESC = (DT == null || DT.Rows.Count < 1) ? string.Empty : DT.Rows[0]["ITEMOFLASTTWODESC"].ToString().Trim();
Response.Write(DESC);
}
}
四、jq: Ajax传递数据到后台C#,後台使用 [System.Web.Services.WebMethod()]
4.1 Default.aspx
<asp:TextBox ID="txb_CALSS_first2Char" runat="server" onkeyup=" return getItemDesc() ; " ></asp:TextBox>
function getItemDesc() {
var item_first2Char = $("#<%=txb_CALSS_first2Char.ClientID%>").val();
var item_next2Char = $("#<%=txb_CALSS_next2Char.ClientID%>").val();
if (item_first2Char.length == 2 && item_next2Char.length == 2) {
var data = "{itemOfTopFour:'" + item_first2Char + item_next2Char + "'}";
var url = "GetItemDesc.aspx/AjaxMethod"
$.ajax({
url: url,//发送到本页面后台AjaxMethod方法
type: "POST",
dataType: "json",
async: true,//async翻译为异步的,false表示同步,会等待执行完成,true为异步
contentType: "application/json; charset=utf-8",//不可少
data: data,
success: function (data) {
var desc = data.d;
if (desc != "" && desc.length >= 2) {
$("#<%=txb_ItemDesc.ClientID%>").val(desc);
}
},
error: function () {
// alert("请求出错处理");
}
});
return true;
} else {
return true;
}
}
4.2 GetItemDesc.aspx.cs
//type方式必须是post,方法必须是静态的,方法声明要加上特性[System.Web.Services.WebMethod()],传递的参数个数也应该和方法的参数相同。
[System.Web.Services.WebMethod()]
public static string AjaxMethod(string itemOfTopFour)
{
itemOfTopFour = itemOfTopFour.Replace("'", "");
string sql = string.Format(@" select ITEMOFLASTTWODESC ,itemOfTopFour from {0} where substr( itemOfTOPfOUR , 0,4 ) ='{1}' ", "itemINFO", itemOfTopFour);
DataTable DT = App_Code.OracleHelper.Query(sql).Tables[0];
string DESC = (DT == null || DT.Rows.Count < 1) ? string.Empty : DT.Rows[0]["ITEMOFLASTTWODESC"].ToString().Trim();
return DESC;
}
5 "使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。
使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了为 maxJsonLength 属性设置的值。
解决办法是在web.config增加如下节点到<configuration>下
<system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="1024000" /> </webServices> </scripting> </system.web.extensions>

浙公网安备 33010602011771号