之前我寫了個ajax提交到ashx一般處理常式!那樣就會又建立一個ashx頁面!而也可以提交到當前頁面,就不要建立一個新的ashx了!但是提交到本頁面,相當於A標籤提交,會做一些無用的操作!因為IsPostBack對ajax請求不起作用! 至於ajax提交到哪個頁面好些!我也不是很清楚!敢興趣的朋友可以去百度,google找下答案!
Default.aspx 頁面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title></title> </head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <script type="text/javascript"> function GetJson() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("您的瀏覽器不支援AJAX!"); return false; } } } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { //alert(xmlHttp.responseText); var str = xmlHttp.responseText; alert(str); //$get("divShow").innerHTML = xmlHttp.responseText; //eval('var s = {"id":1}'); //eval("var s = "+xmlHttp.responseText+")"; // s = { "id": 1 }; try{ eval("var s = " + (str)); alert(unescape(s.Name)); }catch(e){ alert(e.message) } } } var data = "id=1"; xmlHttp.open("POST", "default.aspx?ajax=true", true); xmlHttp.send(data); }</script> <center> <div style="color:Red"> Test <input type="button" value="GetJson" onclick="GetJson();" /> <div id="divShow"></div> </div></center> </form></body></html>
Default.aspx後台
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Test{ public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; if (!string.IsNullOrEmpty(Request.QueryString["ajax"])) { string name = "hao'jiang\"fesd"; string json = "{Id:1,Name:\"" + name.Replace("'", "%27").Replace("\"", "%22") + "\",Sex:\"male\"}";
//嘿,上面的可以使用: string json = "{Id:1,Name:\"" + Server.UrlEncode(name) + "\",Sex:\"male\"}"; Response.Write(json);
/* * 注意:如果你ajax提交的頁面為 aspx,那麼你在Response.Write("")之後還需要 * Response.End();不然你把你需要的字元列印出來了,接著還會把頁面的HTML列印出 * 來,以前我不知道,沒有執行Response.End(),xmlhttprequest.responseText取出來 * 還需要截取字元才對啊! * 所以每次記得 調用Response.End();感興趣的話,把Response.End();注釋掉試一試! * */ Response.End();
//Response.End(); } } }}
Technorati 標籤: ajax提交