asp.net MVC 使用JQuery.Ajax

ASP.NET MVC 使用Jquery Ajax实现登录 视图[Views]  --   Login.cshtml 页面 Ajax Login @*生成防伪标记*@ @Html.AntiForgeryToken() 用户名: 阅读详情

使用到:Jquery.js 以及 Newtonsoft.Json.dll


  客户端调用方式:

$("#ButAjax").click(function() {
            $.ajax({
                type: "POST",  //默认是GET
                url: "/AjaxTest/getPerson",
                data: "ID=1&FirstName=C&LastName=HY",
                async: true,  //异步
                cache: false, //不加载缓存
                success: function(obj) {
                    alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });

        $("#ButAjax2").click(function() {
            $.ajax({
                type: "POST",  //默认是GET
                url: "/AjaxTest/getPerson2?ID=3&FirstName=C&LastName=HY",
                async: true,  //异步
                cache: false, //不加载缓存
                success: function(obj) {
                    alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });

        $("#ButAjax3").click(function() {
            $.ajax({
                type: "POST",  //默认是GET
                url: "/AjaxTest/getString",
                async: true,  //异步
                cache: false, //不加载缓存
                success: function(str) {
                    alert(str);
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });

        $("#ButAjax4").click(function() {
            $.ajax({
                type: "POST",  //默认是GET
                url: "/AjaxTest/getJsonString",
                async: true,  //异步
                cache: false, //不加载缓存
                success: function(str) {
                    var obj = eval(str);
                    $.each(obj, function(item, value) {
                        alert(item + ":" + obj[item]);
                    });
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });

        //================================================================

        $("#ButJson1").click(function() {
            $.getJSON("/AjaxTest/getJson1", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });

        $("#ButJson2").click(function() {
            $.getJSON("/AjaxTest/getJson2", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });

        $("#ButJson3").click(function() {
            $.getJSON("/AjaxTest/getJson3", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });

        $("#ButJson4").click(function() {
            $.getJSON("/AjaxTest/getJsonSerializingJson", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });

        $("#ButJson5").click(function() {
            $.getJSON("/AjaxTest/getJsonDeSerializingJson", { json: '{"ID":201,"FirstName":"C","LastName":"HY","Man":true}' }, function(json) {
                alert(json);
                $.each(json, function(item, value) {
                    alert(item + ":" + json[item]);
                });
            });
        });

 

        //================================================================

        $("#ButSerializing").click(function() {
            $.ajax({
                type: "POST",
                url: "/AjaxTest/testSerializingJson",
                data: "ID=101&FirstName=C&LastName=HY&Man=false",
                async: true,
                cache: false,
                success: function(obj) {
                    alert(obj);
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });

        $("#ButDeSerializing").click(function() {
            $.ajax({
                type: "POST",
                url: "/AjaxTest/testDeSerializingJson",
                data: 'json={"ID":201,"FirstName":"C","LastName":"HY","Man":true}',
                async: true,
                cache: false,
                success: function(obj) {
                    alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });

        $("#ButSerializingList").click(function() {
            $.ajax({
                type: "POST",
                url: "/AjaxTest/serializingList",
                data: "",
                async: true,
                cache: false,
                success: function(obj) {
                    alert(obj + "length:" + obj.length);
                    $.each(obj, function() {
                        $.each(this, function(item, value) {
                            alert(item + ":" + json[item]);
                        });
                    });
                },
                error: function() {
                    alert("请求失败");
                }
            });
        });


Controllers 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication.Controllers
{
    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool Man { get; set; }
    }

    public class AjaxTestController : Controller
    {      
        #region  ===============$.Ajax测试=================
        /// <summary>
        /// 测试返回对象
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public JsonResult getPerson(FormCollection form)
        {
            Person p = new Person
            {
                ID = int.Parse(form["ID"]),
                FirstName = form["FirstName"],
                LastName = form["LastName"]
            };
            return Json(p);
        }

        /// <summary>
        /// 经测试发现:当Global中定义{controller}/{action}/{id}时
        /// 前台url?ID=3&FirstName=C&LastName=HY传到后台时ID值为""
        /// 所以把Global中定义为{controller}/{action}/{uid}
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public JsonResult getPerson2(string ID, string FirstName, string LastName)
        {
            Person p = new Person
            {
                ID = int.Parse(ID),
                FirstName = FirstName,
                LastName = LastName
            };
            return Json(p);
        }

        /// <summary>
        /// 测试返回字符串
        /// </summary>
        /// <returns></returns>
        public ContentResult getString()
        {
            return Content("{id:'2',FirstName:'C',LastName:'HY'}");
        }

        /// <summary>
        /// 测试返回json字符串
        /// </summary>
        /// <returns></returns>
        public ContentResult getJsonString()
        {
            return Content("({id:'2',FirstName:'C',LastName:'HY'})");
        }

        #endregion

        #region ==============$.getJSON(返回json格式测试)============

        /// <summary>
        /// 经测试发现必须是双引号(")不能是单引号(')
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJson1(string ID, string FirstName, string LastName)
        {
            return Content("{\"id\":1,\"name\":\"chy\",\"flag\":true}");
        }

        /// <summary>
        /// 经测试发现必须是双引号(")不能是单引号(')
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJson2(string ID, string FirstName, string LastName)
        {
            return Content("{\"id\":\"2\",\"name\":\"chy\"}");
        }

        /// <summary>
        /// 经测试发现必须是双引号(")不能是单引号(')
        /// 产生错误前台没反应
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJson3(string ID, string FirstName, string LastName)
        {
            return Content("{'id':'3'}");
        }

        #endregion

        #region============Newtonsoft.Json.dll(json序列化和反序列化测试)=============

        /// <summary>
        /// $.Ajax序列化Json
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult testSerializingJson(FormCollection form)
        {
            Person p = new Person
            {
                ID = int.Parse(form["ID"]),
                FirstName = form["FirstName"],
                LastName = form["LastName"]
            };
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
        }      

        /// <summary>
        /// $.Ajax反序列化json
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public JsonResult testDeSerializingJson(FormCollection form)
        {
            Person p = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(form["json"].ToString());
            return Json(p);
        }

        /// <summary>
        /// $.getJSON序列化Json
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <returns></returns>
        public ContentResult getJsonSerializingJson(string ID, string FirstName, string LastName)
        {
            Person p = new Person
            {
                ID = int.Parse(ID),
                FirstName = FirstName,
                LastName = LastName
            };
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
        }

        /// <summary>
        /// $.getJSON反序列化json
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public ContentResult getJsonDeSerializingJson(string json)
        {
            Person p = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(json);
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
        }

        #endregion

        #region================返回集合================

        public JsonResult serializingList()
        {
            List<Person> ls = new List<Person>();
            ls.Add(new Person
            {
                ID = 1,
                FirstName = "C",
                LastName = "HY",
                Man = false
            });

            ls.Add(new Person
            {
                ID = 2,
                FirstName = "Z",
                LastName = "JJ",
                Man = true
            });
            return Json(ls);
        }

        public JsonResult deSerializingList(string json)
        {
            List<Person> listP = new List<Person>();

            List<string> listStr = json.Split(',').ToList<string>();

            foreach (string s in listStr)
            {
                listP.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(s));
            }

            return Json(listP);
        }

        #endregion
    }
}

Asp.Net MVC之jQuery与AJAX操作实例 立即下载

相关推荐

【实战】ESP32 + LN298N 实现电动推杆的闭环位置伺服控制

本文详细介绍了如何使用ESP32微控制器和LN298N电机驱动模块,为普通电动推杆增加编码器反馈,实现精准的闭环位置伺服控制。文章从硬件选型与接线讲起,深入解析了编码器四倍频计数原理与位置换算,并重点阐述了PID控制算法的核心思想、代码实现及参数整定方法,旨在帮助读者从零构建一个反应迅速、定位精准的智能执行器系统。

weixin_29195615的博客 318

asp.net mvc jquery ajax post,使用ASP.NET MVC在JS文件中设置jQuery的ajax url

这样可以充分利用MVC路由,以便充分利用MVC框架。灵感来自于stusmith的答案。在这里我有一个ActionController的动作javascript为这个URL的动作:/application/js我在这里包括静态文件,因为我只需要一个主要的javascript文件下载。你可以选择只要返回动态的东西,如果你想要的:/// /// Renders out javascript/// ///...

weixin_29715563的博客 422

基于STM32平衡小车设计

随着智能硬件的发展,基于STM32的两轮智能平衡车作为一种新型的智能移动工具,具备较高的应用价值。本文旨在设计并实现一款基于STM32微控制器的智能平衡车系统,提升其稳定性和操控性,探索如何通过传感器数据和控制算法实现精确平衡控制。 本设计基于STM32微控制器,选择了STM32F103系列作为核心控制器,具有足够的处理能力和丰富的外设接口。系统通过MPU6050传感器获取三轴加速度和三轴陀螺仪数据,实现实时姿态检测。电机驱动部分采用合适的驱动模块,能够控制两个直流电机,并支持PWM调速。设计中还包括OL

m0_74026776的博客 2731

MVC + JQUERY + AJAX的几种方式

// 传过去一个简单值,获取一个简单值$.ajax({                   type: "GET",                url: ,                  data: "type=11",                 success: function (msg) { alert(msg); }               });   p

935

华北理工大学以升实验班蓝桥杯选拔赛题解

文章目录华北理工大学以升实验班蓝桥杯选拔赛题解A:期末考试题目描述题目讲解代码B:月份题目描述题目讲解代码C:打饭题目描述题目讲解代码D : 正弦波信号题目描述题目讲解代码E : 亲爱的长方形题目描述题目讲解代码F:挖金子题目描述题目讲解代码G : 金金的游戏题目描述题目讲解代码H : 区间和题目描述题目讲解代码详细视频讲解请关注华北理工大学b站账号。 华北理工大学以升实验班蓝桥杯选拔赛题解 A:期末考试 题目描述 Description 期末考试过去许多天了,如今成绩都出来了,那么现在让我们对成绩我分个类

Qq1739206233的博客 1128

避坑指南:从聚宽迁移到QMT必须知道的5个细节(含Redis连接异常处理)

本文详细解析了从聚宽迁移到QMT平台时需注意的5个关键细节,特别是Redis连接池优化和xtquant重连机制。通过实战代码示例,帮助量化团队解决信号传递稳定性、时间同步、滑点控制等核心问题,确保交易策略平稳过渡。

weixin_27303545的博客 430

asp.net中Jquery调用Ajax与asp.net MVC框架中Jquery调用Ajax 总结

以前使用的是js的XMLHttpRequest实现的无刷新技术,最近参考网上整理了一下用Jquery调用Ajax方法,对于熟悉Jquery的人来说是比较容易的,而对于不熟悉的人来说比较困难,闲话少说,看代码  一、asp.net中Jquery调用Ajax  前台代码MyAjax1.aspx为页面名称,AddUsers为后台方法名称       添加用户

haojuntu的专栏 6353

SAP采购信息记录批量维护实战:用BAPI ME_INFORECORD_MAINTAIN搞定价格等级和条件记录

本文深入解析SAP标准BAPI ME_INFORECORD_MAINTAIN在采购信息记录批量维护中的应用,特别聚焦价格等级和条件记录的技术难点。通过实战案例和代码示例,帮助用户高效处理供应商-物料价格数据,提升供应链管理效率。

weixin_42522320的博客 410

.net MVC中Jquery实现AJAX详解

声明 这是我一边学,一边写的: 好处是:我从新手的角度出发,谈自己的理解,每一步的操作也都是按照新手入门来做,有截图。 坏处是:部分地方可能说的不到位或错误。不过作为新手,我觉得能先帮你理解着实现功能貌似更重要。 开始: 0 前言: Ajax本质是一个web数据请求的手段,既然是请求,也就是有请,有求。也就是客户端(html页面)向服务器发送请求获得数据的手段。 世间万物万变不离其宗...

天空 1万+

angular中访问本地json文件

先在assets文件夹下写一个json文件,这样在打完包之后也可以手动修改json文件内容 1、在需要访问本地json文件的ts文件里面引入 import{HttpClient}from'@angular/common/http'; 2、用ajax请求调用,我这里是用已经封装好的ajax请求调用 gethttp = ()=>{ var self = this self.ajax.getAjax("../../assets/server.json","g...

蜗牛~~ 1830

连接参数详解:Connection Interval, Slave Latency, Supervision Timeout 的协同与调优实战

在低功耗蓝牙(BLE)开发与调试中,Connection Interval(连接间隔)、Slave Latency(从机延迟) 和 Supervision Timeout(监督超时) 是三个核心参数。它们不仅直接影响设备的通信性能、功耗表现和连接稳定性,更是各类技术面试与认证考试的高频考点。本文将从基础概念出发,深入剖析三者的协同机制,结合历年真题解析考点与解题思路,并通过实战案例演示调优方法,快速掌握这一核心知识点。

byte轻骑兵的技术小窝 2761

ajax aspx 多参,如何在ASP.NET MVC中使用JQuery.Ajax传递多个参数

嗨,大家好,我是JSon的新手,不太清楚如何传递数据。我正在使用ASP.NET MVC作为我的开发平台。如何在ASP.NET MVC中使用JQuery.Ajax传递多个参数在查看:$(document).ready(function() {$("select#Colors").change(function() {var photoCategory = $("#Colors > option...

weixin_39825722的博客 508

【我的Android进阶之旅】解决android应用使用android:persistent属性带来的系统Launcher应用必须重启设备才生效的问题,大幅度提升开发效率

一、问题描述 我们在开发系统级别应用,比如Launcher桌面的时候,会发现有个问题:每次Launcher修改完代码,重新编译之后,安装到android设备上之后,必须重启才会生效。否则就是使用了之前的Launcher版本的内容。而每次重启设备得一分钟左右,太慢了,太影响效率了! 1.1 痛点 每次更新完代码,重新安装之后,必须重启设备才会生效。效率太TM低了! 二、分析问题 经过一轮代码排查,最终发现是因为src\main\AndroidManifest.xml文件中,定义application使用了an

字节卷动 1713

使用Asp.net MVC, Jquery, Jquery UI构建基于Ajax的RIA应用.

使用Asp.net MVC, Jquery, Jquery UI构建基于Ajax的RIA应用. 前天初学Asp.net MVC,发现有些东西用Web Form来做的确会比较方便. 但Asp.net MVC也有它的优点. 它如果跟Jquery和Jquery UI结合起来做基于Ajax的应用实在是太方便了!!下面用图形说明:这次还是做一个树形控件.需要特别说明的是,这个Demo全部都是用Ajax做的,

shaily读书学习 2271

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

[转]使用jQuery.ajax傳送物件陣列給ASP.NET MVC

本文转自:http://blog.darkthread.net/post-2012-06-23-post-array-to-mvc-with-jquery-ajax.aspx 在ASP.NET MVC裡,我們可以用物件集合當成Action的傳入參數,例如以下範例: 排版顯示純文字複製文字 using System; using System.Collections.Generic;...

weixin_33769125的博客 102

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

asp net mvc ajax上传图片,在asp.net mvc中使用jQuery ajax上传文件

慕容森在ASP.Net MVC中使用AJAX上传文件自HTML5以来,情况发生了变化JavaScript的document.getElementById('uploader').onsubmit=function(){varformdata=newFormData();//FormDataobjectvarfileInput=document.getEle...

weixin_32259697的博客 415

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

使用jQuery.Ajax向ASP.NET MVC控制器Post数据

jQuery自带了Ajax的函数,你可以使用它从远程服务器下载网页,但问题是,大部分Ajax都是通过GET这种方式与远程服务器交互的。 但如果你想通过Ajax向远程服务器传递数据呢?当然jQuery.Ajax里面有一个参数data参数允许你传递发送到服务器的数据。但问题是,这个数据默认是采用GET方式,即附加在请求字符串(URL QueryStri...

weixin_33766805的博客 267

asp.net ajax提交表单,ASP.Net MVC,使用JQuery.Ajax提交表单

我想使用JQuery Ajax提交表单(Html.BeginForm())。 根据this question,它应该工作! 我不明白为什么来自动作SendEmail()的参数'email'没有从js获取值。 你能帮我吗?ASP.Net MVC,使用JQuery.Ajax提交表单笔者认为:{ %>De...A... Model.Agent.Email, new { @id = "MailTo"...

weixin_36145011的博客 489

asp.net mvc jquery ajax post,使用ASP.NET MVC在JS文件中为jQuery设置ajax url

小编典典这种方式充分利用了MVC路由,因此您可以充分利用MVC框架。受斯图史密斯答案的启发。在这里,我有一个ApplicationController针对此URL的动态javascript 操作:/application/js我在此处包括静态文件,因为我只想下载一个主Javascript文件。您可以根据需要选择只返回动态内容:/// /// Renders out javascript/// //...

weixin_29015899的博客 355

ajax显示数据库asp.net,从数据库中获取数据并使用Ajax,Jquery,Asp.Net以表格格式显示MVC...

我已经建立了与数据库的连接,并且我希望在表格格式的视图中显示数据库中的所有详细信息,但是无法做到这一点,因为我的新人可以帮助任何人。从数据库中获取数据并使用Ajax,Jquery,Asp.Net以表格格式显示MVCpublic class EmployeeModel{public int EmpId { get; set; }public string EmpName { get; set; }p...

weixin_39645308的博客 380

使用Asp.net MVC, Jquery, Jquery UI构建基于Ajax的RIA应用.(更新Demo下载)

前天初学Asp.net MVC,发现有些东西用Web Form来做的确会比较方便. 但Asp.net MVC也有它的优点. 它如果跟Jquery和Jquery UI结合起来做基于Ajax的应用实在是太方便了!!下面用图形说明: 这次还是做一个树形控件.需要特别说明的是,这个Demo全部都是用Ajax做的,增删改都无刷新,而且可以方便地换肤..以下是最终的效果图: 新建分类. 用上Effe...

weixin_34410662的博客 132

asp.net mvc jquery ajax post,在asp.net mvc中使用jQuery ajax上传文件

自HTML5以来,情况发生了变化JavaScript的document.getElementById('uploader').onsubmit=function(){varformdata=newFormData();//FormDataobjectvarfileInput=document.getElementById('fileInput');//Iterating...

weixin_35774805的博客 238

asp.net MVC3 + JQuery 的ajax简单使用

asp.net MVC3 + JQuery 的ajax简单使用 一直都没有使用过JQuery,更没使用过JQuery的ajax支持带来的方便,今天试了一下,真是减少了很多工作量,使用方法也比较简单 这里先记下来,以后使用时可以再拿着用。 本应用中,本来是准备使用长链接的方式,在server端有错误消息产生时,能实时返回错误消息。可在使用长链接时,因为.net功底 不够,以失败告终!...

ikeycn的专栏 282
上一篇: (转)Expression Blend实例中文教程系列文章汇总
下一篇: asp.net MVC 使用Ext.Ajax.request
黑暗行动
博客等级 码龄19年 231粉丝 554原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值