1. 程式人生 > >ashx一般處理程式接收ajax傳回的json字串,並寫入到資料庫

ashx一般處理程式接收ajax傳回的json字串,並寫入到資料庫

首先將json物件轉為json字串

var aToStr = JSON.stringify(graphicStr);   //json轉字串

然後ajax 通過post請求

$.ajax({
                    type: 'post',
                    url: 'saveG.ashx',
                   
                    data: aToStr,
                    dataType:'text ',
                 
                    success: function () { alert('成功了!'); },
                    
                });

在ashx.cs檔案中

using System;


using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.IO;


using System.Data.SqlClient;//必須引入
using System.Collections.Generic;
using System.Text;




namespace WebApplication1
{
    public partial class saveG : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //接收字串
            string strJSON = string.Empty; 
            using (StreamReader reader = new StreamReader(Context.Request.InputStream))
            {
                strJSON = reader.ReadToEnd();
            } 
            Context.Response.Write(strJSON);
            

            //連線字串
            string myconn = "Server=資料庫地址;Database=資料庫名稱;User ID='使用者名稱';Password='密碼'";
            
            //建立資料庫連線。
            SqlConnection myconnection = new SqlConnection(myconn);
            
            //開啟資料庫連線
            myconnection.Open();


            string sql = "SELECT * FROM [zhouhaitest].[dbo].[test]";
            
            SqlCommand cmd = new SqlCommand(sql, myconnection) ;
           
            //寫入資料庫
            cmd.CommandText = "INSERT into [zhouhaitest].[dbo].[test] values  (newid(),@GRAPHIC)";    //需要執行的sql語句
            cmd.Parameters.Add("@GRAPHIC ", SqlDbType.Text).Value = strJSON; 
            cmd.CommandType = CommandType.Text;
            cmd.Connection = myconnection;
            try
            {
               
                cmd.ExecuteNonQuery();
                Response.Write("</br>寫入成功");
            }
            catch (Exception ex)
            {
                Response.Write("寫入失敗");
                
            }
            finally
            {
                myconnection.Close();
            }
        }

    }
}