mvc的action中如何获取ajax post过来的数据?Request Payload

我网上下载的demo,在action中可以获取到前端post过来的数据
图片说明

图片说明
但是,怎么在我的mvc2程序中获取不到啊?
图片说明

1个回答

你用Request.Form["take"]看能不能获取

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

mvc4中ajax请求重定向问题

在mvc4中我有一个过滤器 在每一个action前都会先调用一次,里面的方法是用来判断用户是否登录如果是程序发出的请求还好可以重定向到登录页面 但ajax 的请求就无法重定向,我现在有一个解决方法但是 还是不完美 这是我的过滤器,如果是ajax的请求就在浏览器头部设置一个标记 ``` protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (UserInfo == null) { //如果是Ajax 请求的 要特殊处理 if (HttpContext.Request.IsAjaxRequest()) { //添加头部信息 前端会有ajax回调 判断 Response.AddHeader("sessionstatus", "timeout"); return; } else { //正常的请求 filterContext.Result = new RedirectToRouteResult( "Default", new RouteValueDictionary( new { controller = "Login/Login", action = "Login" })); } } else { base.OnActionExecuting(filterContext); } } ``` 如果标记是ajax的就 在我的js 里设置一段全局的 js代码 如果是标记的 就用js 来定向 登录页面 ``` /** * 设置未来(全局)的AJAX请求默认选项 * 主要设置了AJAX请求遇到Session过期的情况 */ $.ajaxSetup({ type: 'POST', complete: function (xhr, status) { var sessionStatus = xhr.getResponseHeader('sessionstatus'); if (sessionStatus == 'timeout') { //var yes = confirm('由于您长时间没有操作, session已过期, 请重新登录.'); //if (yes) { window.location.href = '/Login/Login/Login'; // } } } }); ``` 那么问题来了 我这里 设置完标记后 js也重定向了 但是 我请求的 query 这个查询方法 必须要 全部执行完 才重新定向登录页面 下面这个 方法会执行 ``` public string Query() { //string BeginDate = Request.Form["BeginDate"]; //string EndDate = Request.Form["EndDate"]; string MemberNO = Request.Form["MemberNo"]; string MemberName = Request.Form["MemberName"]; int pageIndex = Request.Form["page"] != "" ? Convert.ToInt32(Request.Form["page"]) : 0; int pageSize = Request.Form["rows"] != "" ? Convert.ToInt32(Request.Form["rows"]) : 0; StringBuilder WhereCode = new StringBuilder(" CompanyID = "+this.UserInfo.CompanyID); //if (!string.IsNullOrEmpty(BeginDate)) //{ // WhereCode.Append(" AND (RegisterDate >= '" + BeginDate + "')"); //} //if (!string.IsNullOrEmpty(EndDate)) //{ // WhereCode.Append(" AND (RegisterDate <= '" + EndDate + "')"); //} if (!string.IsNullOrEmpty(MemberNO)) { WhereCode.Append(" AND MemberNo ='" + MemberNO + "'"); } if (!string.IsNullOrEmpty(MemberName)) { WhereCode.Append(" AND MemberName like '%" + MemberName + "%'"); } WhereCode.Append(" AND (Status = 'A') AND (MemberType = '01')"); MemberService memberInfo = new MemberService(); string json = memberInfo.GetMemberInfo(WhereCode.ToString(), pageIndex, pageSize); return json; } ``` 不是 谁有好的解决方案 如果我是ajax 的请求 就让请求 不继续 执行 直接重定向

Spring MVC WEB工程中前后台post传值事该不该用@RequestBody?

最近在做一个项目,BS架构用的SpringMVC,在做前后台交互时用post将前台的数据发送到后台,对action里面的@RequestBody有点迷糊,求教各位大神。 ``` @RequestMapping(value = "/something", method = RequestMethod.POST) public void handle(@RequestBody User user, Writer writer) throws IOException { writer.write(body); } ``` 这样用AJAX提交时必须是下面这种才能成功 ``` var user={'name':name,'passwd':passwd} $.ajax({ url : "http://localhost:8080/something", type : "POST", contentType: "application/json", data : JSON.stringify(user), dataType : "json", success : function(result) { }, error:function(msg){ } }); ``` 如果后台action里面取掉@RequestBody,就像下面这样 ``` @RequestMapping(value = "/something", method = RequestMethod.POST) public void handle( User user, Writer writer) throws IOException { writer.write(body); } ``` 前台post数据的时候直接这样就行了 ``` var user={'name':name,'passwd':passwd} $.ajax({ url : "http://localhost:8080/something", type : "POST", data : user, success : function(result) { }, error:function(msg){ } }); ``` 这样就可以收到前台传过来的值,但是按照前面的就不行了。 这个里面@RequestBody到底有什么作用,我的本意是后台直接接收一个User对象,如果按照第一种方法,感觉像是我前台先创建一个User对象,然后把它转成了JSON串再post到后台,然后通过@RequestBody再将JSON串转换成User对象,这感觉有点多此一举。而第二种方法感觉就是直接把对象传到后台的。那么这里@RequestBody的作用是什么。感觉第二种更加的方便,可是我看了一些人说的和一些项目中例子,用的第一种的比较多,这是为什么,百思不得其解?

MVC中的AJAX超时问题

<div class="post-text" itemprop="text"> <p>I have an ASP.Net MVC application. I am using an AJAX request on a page which requires user authentication to fire an action on another controller, which returns a view to update a table on the page. The action that the AJAX request makes also requires authentication. The issue comes up when the user lets their session timeout and then does something to fire the AJAX request. The entire page does not redirect to the login page. Instead, the view returned to the AJAX request is the login page, which then is populated inside the div meant for the refreshed data table.</p> <p>Is there a way to at least have the request return an error message instead of the login view?</p> </div>

请问asp怎么获取和处理ajax传过来的formdata数据呢? 我是想存到本地

html大概的结构: ``` <form id="uploadForm" action="uploadImg.ashx" method="post" enctype="multipart/form-data"> <input id="fileImage" type="file" size="30" name="fileselect[]" multiple /> <button type="button" id="fileSubmit" class="upload_submit_btn">确认上传图片</button> ``` Ajax: ``` for (var i = 0, file; file = this.fileFilter[i]; i++) { (function(file) { var formData = new FormData(); formData.append(file.name,file); $.ajax({ url: self.url, type: 'post', data: formData, contentType: false, processData: false, success: function(data) { self.onSuccess(data); self.funDeleteFile(file); }, error: function(data) { console.log("error"); self.onFailure(file); } }) if(!self.fileFilter.length){ //执行完成 self.onComplete(); } })(file); } } ``` 请问我的ashx里面怎么写才可以存入到本地呢?另外也得从本地读取图片然后用ajax传回给html,请问有没有例子示范下,谢谢

MVC后台接收不到表单提交的数据

1:MVC后台接收不到表单提交的数据 ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>login test</title> </head> <body> <div id="form-div"> <form id="form1" action="login" method="post"> <p>用:<input name="userName[1]" type="text"/></p> <p>密:<input name="userName[3]" type="text"/></p> <p><input type="submit" value="登录"></p> </form> </div> </body> </html> ``` 后台接收 ``` public ActionResult login(string[] userName) { } ```

asp.net mvc怎么对post提交的编码了的参数字符串解码?

安卓客户端用HttpUrlConnection以post请求,对数据进行了Urlencode ``` String param="beginId="+beginNumber+"&dataRequestType=dataRequest"; //这里beginNumber是一个变量,对这个字符串进行了urlencode String paramEncode= URLEncoder.encode(param,"UTF-8"); //这个字符串编码后作为http报文的正文内容传递 ``` 然后在asp.net mvc的controller的action中接收 ``` var begin = Request["beginId"]; if (begin == null) beginId = 0; ``` 但是目前来看,不管客户端传的是什么beginId的值是什么,都只能获取到beginId为0时的结果,我猜想可能是客户端对http报文正文内容,作为post方式提交的参数字符串进行了编码,但是服务端没解码的原因致使不能获取到beginId的值。求教asp.net mvc怎么对http的进行了urlencode的post方式的参数字符串进行解码,并正确获得参数的值?

用jquery ajax从数据库获取数据实现二级联动

我的思路就是一级那里搞个select,然后利用ajax返回action。然后利用ajax那里不懂。哪位大神教我怎么做? 1、这是select, function select(){ var xitong=document.getElementById("xitong").value; $.ajax({ url:'/netbank/budiao/testaj', type:'post', dataType:'json', data:{"xitong.xitongname":xitong}, error: function(){ alert("服务器没有返回数据,可能服务器忙,请重试"); }, success:createshebeiname2 }); 2、这是/netbank/budiao/testaj', public String testaj(){ System.out.println("testaj"); String name=xitong.getXitongname(); System.out.println(name); shebeilist=budiaoBiz.getShebeibyname(xitong.getXitongname()); request.put("shebeilist", shebeilist); return "testaj"; } 3、这是struts.xml的一部分 <package name="budiao" namespace="/budiao" extends="json-default" > <action name="*" class="budiao" method="{1}"> <result name="testaj" type="json"></result> 结果:select选择的时候,能够打印出testaj和xitongname的值,还有alert("服务器没有返回数据,可能服务器忙,请重试");

MVC AJAX POST设计问题

<div class="post-text" itemprop="text"> <p><strong>Question background:</strong></p> <p>I have a page in my MVC app that allows a user to submit a question as shown:</p> <p><img src="https://i.stack.imgur.com/QpXKD.jpg" alt="enter image description here"></p> <p>Once the Send button has been pressed a Modal Pop-up displays with a Spinner to show the message is being sent then once successfully sent the modals contents will be changed to reflect this with a appropriate message.</p> <p><strong>Potential Design Concerns:</strong></p> <p>Currently I am using AJAX to post the textbox values to a controller called <code>Contact</code> which has a method called <code>SendMail</code></p> <p>AJAX POST function:</p> <pre><code>&lt;script&gt; $("#SendMessage").click(function (e) { $("#SendingModal").modal('show'); $.ajax({ url: '@Url.Action("SendMail")', type: 'POST', data: { "name": $('#name').val(), "email": $('#email').val(), "subject": $('#subject').val(), "message": $('#message').val() }, success: function () { $('#contactForm').html('&lt;div class="row"&gt;' + '&lt;div class="col-lg-12 col-md-12 col-sm-12"&gt;' + '&lt;div class="jumbotron jumbotronPadding"&gt;' + '&lt;h2&gt;Message sent&lt;/h2&gt;' + '&lt;p&gt;&lt;h3&gt;Thank your for your enquiry, we will reply as soon as possible.&lt;/h3&gt;&lt;/p&gt;' + '&lt;/div&gt;' + '&lt;/div&gt;' + '&lt;/div&gt;'); $('#SendingModal').modal('hide'); } }); }); </code></pre> <p></p> <p>The <code>SendMail</code> method that takes the parameters sent from the Contact page through the AJAX POST request:</p> <pre><code> public void SendMail(string name, string email, string subject, string message) { var mailMessage = new EmailContactHandler(); mailMessage.SendMail(name, email, subject, message); } </code></pre> <p>Should I be using a <code>Html Form</code> instead of the current AJAX call? Currently I'm posting each individual textbox value to its relevant parameter value on the <code>SendMail</code> method i.e name, email, subject, message. A Form would allow me to send these by a <code>ViewModel</code>. Is my current implementation ok? If not what would be a better method (ideally using some sort of model)</p> <p><strong>Update:</strong></p> <p>After reading Mackans answer I have refactored the code to map to a model called Contact to the set data properties in the AJAX request.</p> <p>AJAX request:</p> <pre><code>&lt;script&gt; $("#SendMessage").click(function (e) { $("#dialog-example").modal('show'); $.ajax({ url: '@Url.Action("SendMail")', type: 'POST', data: { name: $('#name').val(), email: $('#email').val(), subject: $('#subject').val(), message: $('#message').val() }, success: function (message) { if (message.messageStatus === "success") { $('#contactForm').html('&lt;div class="row"&gt;' + '&lt;div class="col-lg-12 col-md-12 col-sm-12"&gt;' + '&lt;div class="jumbotron jumbotronPadding"&gt;' + '&lt;h2&gt;Message sent&lt;/h2&gt;' + '&lt;p&gt;&lt;h3&gt;Thank your for your enquiry, we will reply as soon as possible.&lt;/h3&gt;&lt;/p&gt;' + '&lt;/div&gt;' + '&lt;/div&gt;' + '&lt;/div&gt;'); } $('#dialog-example').modal('hide'); } }); }); </code></pre> <p></p> <p>Contact model:</p> <pre><code>public class Contact { public string Name { set; get; } public string Email { set; get; } public string Subject { set; get; } public string Message { set; get; } } </code></pre> <p>The <code>SendMail</code> method on the controller that now takes an model instance called Contact.</p> <pre><code> public ActionResult SendMail(Contact emailMessage) { var mailMessage = new EmailContactHandler(); mailMessage.SendMail(emailMessage); return Json(new { messageStatus = "success"}); } </code></pre> </div>

当请求方法是GET但在POST方法中失败时,为什么这个ajax请求成功

<div class="post-text" itemprop="text"> <p>When I set the request type to "GET",(and also use $_GET on server side), it successfully fetches the response, but gives a <code>400 error</code>, <code>Missing required parameters: student_id</code> when I set the type to POST.</p> <p>Here's the code :</p> <pre><code>$.ajax({ type: "GET", url: "?r=fees/fees/transactions", dataType: "json", data: { student_id: student_id }, success:function( msg ) { console.log(msg); }, error: function(xhr, ajaxOptions, thrownError){ console.log("failed"); console.log(xhr.responseText); console.log(ajaxOptions); console.log(thrownError); } }); </code></pre> <p>Here is the request URL when I set the request method to GET: </p> <p><code>http://localhost/demo.git/index.php?r=fees/fees/transactions&amp;_csrf=bEJJWVowdl8jBwQjaUMsAA52eT8MXBMLJigwHTxeKSlVKyxoD2o5KQ%3D%3D&amp;student_id=10115"</code>. </p> <p>why doesn't this work when I set the above request type to POST and receive the variable on server side by POST method?</p> <p>Here is the server side action (I am using Yii2 MVC framework)</p> <pre><code>public function actionTransactions($student_id){ $student_id = $_POST['student_id']; ... ... echo json_encode($response); } </code></pre> </div>

mvc 下 jquery post提交 action 得不到值 值为null

前台js var ddd = function () { $.post("/Home/ttt", { "d": 1 }, function (result) { alert(result); }, 'json'); $.ajax({ type: "POST", url: "/Home/ttt", data: { "d": 1, }, dataType: "json", success: function (data) { alert(data); }, error: function (json) { alert("订单取消异常,请刷新后重试..."); } }); }; ``` [HttpPost] public JsonResult ttt(string d) { string sd = Request.QueryString["d"]; return Json(new { f = 1 }); //return View(); } ``` 哪位大神知道怎么回事

ajax校验数据库数据是否存在

``` <!-- 查询student_id是否存在 --> <select id="getStudent_id" resultMap="studentMap" parameterType="int"> SELECT * from student where student_id = #{student_id} </select> ``` ``` @RequestMapping("/studentID") public Student getStudent_id(Integer student_id) { Student student = userService.getStudent_id(student_id); if (student==null){ System.out.println("没有"); }else{ System.out.println("有"); } return student; } ``` ``` function check() {//js表单验证方法 var text = document.getElementById("xh").value;//通过id获取需要验证的表单元素的值 if (text == "") { alert("请输入学号!");//弹出提示 return false;//返回false(不提交表单) } if (!(/(^[1-9]\d*$)/.test(text))) { alert("请输入学号!");//弹出提示 return false;//返回false(不提交表单) } var student_id=$("#student_id").val(); $.ajax({ url:"<%=basePath%>user/studentID", type:"post", data:{"student_id":student_id}, dataType:"json", success:function(data){ if (data!=null ) { alert("有"); }else if(data==null && username !=''){ alert("没有"); } xmlhttp.open("GET","getcustomer.asp?q="+str,true); xmlhttp.send(); //alert("啊啊啊"); } }); return true;//提交表单 } </script> <body> <div class="listDIV"> <table border="1" width="50%" height="50%" style="text-align: center;"> <form action="<%=basePath%>user/one" method="post"> <input type="text" id="xh" name="student_id" placeholder="根据学号查询"> <button class="glyphicon glyphicon-select" onclick="return check();">查询</button> </form> ``` ``` 严重: Servlet.service() for servlet [springMVC] in context with path [/StudentManagementSSM] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at com.zmk.controller.UserTestController.getStudent_id(UserTestController.java:65) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1139) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) ``` 我用ssm做的增删改查,搜索我想先校验一下数据库数据是否存在,存在就直接跳转查询,不存在就弹窗提示,中止提交表单,JS代码是我粘过来的,不会JS,有错误希望能告诉我如何改正,谢谢

带有Spring-MVC的Ajax POST

<div class="post-text" itemprop="text"> <p>These days I have had an issue and I couldn't solve it yet. I have a shopping cart, and it works with jQuery. So I get the products in a GET petition (I use Spring-MVC), and then I add products into the cart with jQuery. Finally I want to send this data (I mean, product id, quantity, etc) to my Spring Controller, and I've tried to use an Ajax petition. Below I show you the code. Notice that if I use $(selector).click(), I can show the data in the controller, but if I use $(selector).submit(), I have a lot of problems. I think I really don't understand how it works, so I would need help.</p> <p>Controller</p> <pre><code>@PostMapping(value = "/carrito", consumes = {"application/json", MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = "application/json") //produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public @ResponseBody String confirmaCarrito(@RequestBody ProdAJAX prod) { System.out.println("X: " + prod.getX()); System.out.println("Y: " + prod.getY()); return "redirect:/home"; } </code></pre> <p>HTML</p> <pre><code> &lt;form th:action="@{/pedido/carrito}" th:object="${cliente}" method="post"&gt; &lt;!-- Product list --&gt; &lt;div class="col-sm-4"&gt; &lt;h2&gt;Carrito&lt;/h2&gt; &lt;!-- Elementos del carrito --&gt; &lt;ul id="carrito" class="list-group"&gt;&lt;/ul&gt; &lt;hr&gt;&lt;/hr&gt; &lt;!-- Precio total --&gt; &lt;p class="text-right"&gt; Total: &lt;span id="total"&gt;&lt;/span&gt;&amp;euro; &lt;/p&gt; &lt;input type="submit" value="Confirmar" id="confirmaCarrito" class="btn btn-crear"&gt;&lt;/input&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>jQuery</p> <pre><code>&lt;script&gt; $(document).ready(function() { let i = 0; $(".addButton").click(function() { var miNodo = $("&lt;li&gt;&lt;/li&gt;"); var miProd = $("&lt;span&gt;&lt;/span&gt;") var miCant = $("&lt;input&gt;&lt;/input&gt;"); var miPrecio = $("&lt;span&gt;&lt;/span&gt;"); miNodo.attr("posicion", i); miNodo.attr("class", "nodo list-group-item text-right"); miProd.attr("name", "prod"); miProd.attr("idProd", $(this).attr("id")); miProd.text($(this).attr("name")); miCant.attr("idCant", $(this).attr("id")); miCant.attr("type", "number"); miCant.attr("class", "cant"); miCant.attr("value", 1); miCant.attr("name", "cant"); miPrecio.attr("idPrecio", $(this).attr("id")); miPrecio.text($(this).attr("precio")); miNodo.append(miProd); miNodo.append(miCant); miNodo.append(miPrecio); $("#carrito").append(miNodo); i = i + 1; }); $("#confirmaCarrito").submit(function(event) { //data["id"] = $(".nodo").attr("idNodo"); //data["id"] = 5; //data["cant"] = $(".cant").attr("value"); //var prod = $("prod").attr("idProd"); //var cant = $(".cant").val(); //var data = idProd.concat(",", cant); var data = { "x" : 100, "y" : 200 }; $.ajax({ type : "POST", contentType : "application/json; charset=UTF-8", url : "/pedido/carrito", data : JSON.stringify(data), dataType : "json", success : function(data) { if (data == "SUCCESS") { alert(data); } else { alert(data); } } // timeout: 600000, //async : true, }); event.preventDefault(); }); }); </code></pre> <p></p> <p>Actually if I use .click() it works, but if I use .submit() it doesn't work. Thanks!</p> </div>

SpringMVC的@Requestbody接收不到json的值

控制层 @Controller @RequestMapping("/task") public class TaskAction { @RequestMapping("/run") public @ResponseBody TaskConnects runTask(@RequestBody TaskConnects connects)throws Exception{ System.out.println("----------------------" + "\n" + connects); return connects; } } js的代码 $.ajax({ type: "post", url: "task/run.action", contentType:'application/json;charset=utf-8', data: '{"ConnectionId":"con_12","SourceId":"circle-1","TargetId":"roundedRect-3"}', datatype: "json", success: function () { alert("send successfully") } SpringMVC配置文件也加了json转换器 <!-- json转换器 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter" /> </list> </property> </bean> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <mvc:annotation-driven />

获取AJAX响应的特定部分

<div class="post-text" itemprop="text"> <p>When i inspect the response from my AJAX request to index.php, I get back some data that i want (some json, a return value i need the value of) but also a load of HTML as the index.php class is used to call a view which is responsible for loading up some HTML. </p> <p>Here is the first two lines of the response:</p> <pre><code>{"returnVal":"registered"}&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; </code></pre> <p>Due to my code being MVC, i cannot just create a separate file to handle the AJAX request, so i need a way for my login.js class (where the AJAX request is generated) to go through the whole response and find the value of "returnVal" that I need. Do you know of a way I can do this?</p> <p>Login.js</p> <pre><code>var loginData, urlPath; // Allow users to log in or register function Login() { if(!document.getElementById("usernameField")) { // If we have no username field on this page, we are just logging in loginData = "email=" + $("#emailField").val() + "&amp;password=" + $("#passwordField").val() + "&amp;action=" + "loggingIn"; urlPath = "index.php"; } else { // we are registering loginData = "username=" + $("#usernameField").val() + "&amp;email=" + $("#emailField").val() + "&amp;password=" + $("#passwordField").val() + "&amp;action=" + "register"; urlPath = "../index.php"; } // Send the login/registration data to database $(document).ready(function() { $.ajax({ type: "POST", url: urlPath, data: loginData, success: function (result) { alert(result); // i need to get the value of 'returnVal' from the response if(result.returnVal=="registered") { document.getElementById('notification').innerHTML = "You have been registered"; } else if (result.returnVal=="username") { document.getElementById('notification').innerHTML = "Username already taken"; } else if (result.returnVal=="email") { document.getElementById('notification').innerHTML = "Email already taken"; } else if (result.returnVal=="notRegistered") { document.getElementById('notification').innerHTML = "Please enter registered email"; } else if (result.returnVal=="loginFail") { document.getElementById('notification').innerHTML = "Please enter correct password"; } else if (result.returnVal=="loggedIn") { $('#myModal').modal('hide'); document.getElementById('loginButton').innerHTML = "Account Settings"; } else { // Something wrong, tell us //alert(result); } }, error: function(xhr, status, error) { alert(xhr.responseText); } }) }) } </code></pre> <p>index.php</p> <pre><code>&lt;?php ini_set("log_errors", 1); require_once("Model/model.php"); require_once("Controller/controller.php"); require_once("View/view.php"); $model = new Model(); $view = new View(); $controller = new Controller($model, $view); if(isset($_POST['action'])) { if($_POST['action'] == "register") { $controller-&gt;Register($_POST['username'], $_POST['email'], $_POST['password']); echo json_encode($controller-&gt;GetReturned()); } } $view-&gt;Begin(); ?&gt; </code></pre> </div>

MVC自动完成ajax

<div class="post-text" itemprop="text"> <p>Try to:</p> <pre><code>$(document).ready(function () { $('#cityName').autocomplete({ source: function(request,response) { $.ajax({ type: 'POST', url: '@Url.Action("Search", "City")', dataType: 'json', data: { name: request.term } , success: function (data) { response($.map(data, function (item) { alert(JSON.stringify(data)); alert(JSON.stringify(item.name)); return { name: item.name, label: item.name } })); } }) }, messages: { noResults: "", results: "" } }) }) </code></pre> <p>In <code>alert(JSON.stringify(data))</code> got this: {"items":["Boston","Berlin"]}. In <code>alert(JSON.stringify(item.name))</code> got this: undefined.</p> <p>Question: how do it (item.name) works?</p> </div>

将数据发送到服务器

<div class="post-text" itemprop="text"> <p>I recently perform some ajax request on my website but I'm still beginner.</p> <p>Here is a stupid question: How to send (POST) a data to the server without waiting any response ? </p> <p>In all the example I found on internet, the ajax call is used to reload a part of the page. It work perfectly, but my idea here is just to send a data that could be store in DB for example without waiting any response.</p> <p>I'm using Zend framework with MVC pattern. I tried something like:</p> <pre><code>$.ajax({ type: "POST", url:'/controller/action', data: { myDataToPost: aData }, success:function(response){ }, failure:function(){ alert('Could not save your entry'); } }); </code></pre> <p>It works fine if I define an action in my controller but I can see in firebug an 404 error on controller/action page. For sure it doesn't exist because i don't want any response...</p> <p>Many thanks for your help! Cedric.</p> </div>

mvc3 ajax预填充文本框

<div class="post-text" itemprop="text"> <p>I have a controller that uses <strong>ajax.actionlink</strong> in order to get a partial view from another controller. My question is how can I use the <strong>result from that ajax partialview to fill in a textbox in my main action</strong> . </p> <p>This is the <strong>view i'm working on</strong> corresponds to this view</p> <pre><code>@Ajax.ActionLink("Find location", "getzipcode", new AjaxOptions { UpdateTargetId = "ajax_insert", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }); &lt;div id="ajax_insert"&gt; &lt;/div&gt; @using (Html.BeginForm("create", "service", FormMethod.Post)) { // fill Ajax code in this EditFor Result @Html.EditorFor(model =&gt; model.zipcode) } </code></pre> <p>as you can see above that ajax simply request's a partial view called <strong>getzipcode</strong> which just links to this action</p> <pre><code>public PartialViewResult getzipcode() { var zipco = (from s in db.servicers where s.zipcode == 32839 select s); return PartialView("_review", zipco); } </code></pre> <p>The ajax works correctly, im just stumped on inserting the zipcode into the EditFor box as well I tried <strong>@Html.EditorFor(model =&gt; model.zipcode,@ajax_insert)</strong> but it did not work.</p> </div>

Jquery Ajax 调用和 Html.AntiForgeryToken ()

<div class="post-text" itemprop="text"> <p>I have implemented in my app the mitigation to <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="noreferrer">CSRF attacks</a> following the informations that I have read on some blog post around the internet. In particular these post have been the driver of my implementation</p> <ul> <li><a href="http://blogs.msdn.com/b/aspnetue/archive/2010/09/17/second_2d00_post.aspx" rel="noreferrer">Best Practices for ASP.NET MVC</a> from the ASP.NET and Web Tools Developer Content Team</li> <li><a href="http://haacked.com/archive/2009/04/02/anatomy-of-csrf-attack.aspx" rel="noreferrer">Anatomy of a Cross-site Request Forgery Attack</a> from Phil Haack blog</li> <li><a href="http://davidhayden.com/blog/dave/archive/2009/04/29/AntiForgeryTokenInMVCFramework.aspx" rel="noreferrer">AntiForgeryToken in the ASP.NET MVC Framework - Html.AntiForgeryToken and ValidateAntiForgeryToken Attribute</a> from David Hayden blog</li> </ul> <p>Basically those articles and recommendations says that to prevent the CSRF attack anybody should implement the following code:</p> <p>1) Add the <code>[ValidateAntiForgeryToken]</code> on every action that accept the POST Http verb</p> <pre><code>[HttpPost] [ValidateAntiForgeryToken] public ActionResult SomeAction( SomeModel model ) { } </code></pre> <p>2) Add the <code>&lt;%= Html.AntiForgeryToken() %&gt;</code> helper inside forms that submits data to the server</p> <pre><code>&lt;div style="text-align:right; padding: 8px;"&gt; &lt;%= Html.AntiForgeryToken() %&gt; &lt;input type="submit" id="btnSave" value="Save" /&gt; &lt;/div&gt; </code></pre> <p>Anyway in some parts of my app I am doing Ajax POSTs with jQuery to the server without having any form at all. This happens for example where I am letting the user to click on an image to do a specific action. </p> <p>Suppose I have a table with a list of activities. I have an image on a column of the table that says "Mark activity as completed" and when the user click on that activity I am doing the Ajax POST as in the following sample:</p> <pre><code>$("a.markAsDone").click(function (event) { event.preventDefault(); $.ajax({ type: "post", dataType: "html", url: $(this).attr("rel"), data: {}, success: function (response) { // .... } }); }); </code></pre> <p>How can I use the <code>&lt;%= Html.AntiForgeryToken() %&gt;</code> in these cases? Should I include the helper call inside the data parameter of the Ajax call?</p> <p>Sorry for the long post and thanks very much for helping out</p> <p><strong>EDIT</strong>:</p> <p>As per <a href="https://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken/4074289#4074289">jayrdub</a> answer I have used in the following way</p> <pre><code>$("a.markAsDone").click(function (event) { event.preventDefault(); $.ajax({ type: "post", dataType: "html", url: $(this).attr("rel"), data: { AddAntiForgeryToken({}), id: parseInt($(this).attr("title")) }, success: function (response) { // .... } }); }); </code></pre> </div> <p>转载于:https://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken</p>

Ajax请求关闭MVC表单

<div class="post-text" itemprop="text"> <p>I am trying to do an ajax request and depending on the ajax request results I will allow the form to submit to the controller. However everytime the ajax request runs I get the error message. </p> <p>Here is my javascript function:</p> <pre><code>function CheckForValidation(e) { var scholarshipRequest = $("#scholars").val(); var aidYearRequest = $("#aidYear").val(); var amountRequest = $("#amount").val(); $.ajax({ type: "POST", url: '@Url.Action("Validate_ScholarshipRequest", "RequestController")', data: { scholarshipId: scholarshipRequest, aidYear: aidYearRequest, amount: amountRequest } }).success(function(response) { if (!response.success) { e.preventDefault(); alert(success); } else { e.preventDefault(); } }).error(function() { e.preventDefault(); alert("Error on Submission"); }); } </code></pre> <p>This function is called from here:</p> <pre><code>$("#SubmitTutorRequestFrm").submit(function(e) { e.PreventDefault(); CheckForValidation(e); }); </code></pre> <p>I try to debug the code and put a breakpoint on Validate_ScholarshipRequest but that method never gets called. The method signature is:</p> <pre><code>public ActionResult Validate_ScholarshipRequest(string scholarshipId, string aidYear, string amount) </code></pre> <p>This is the start of my form:</p> <pre><code>@using (Html.BeginForm("SubmitScholarshipRequest", "Request", FormMethod.Post, new { id = "SubmitTutorRequestFrm" })) </code></pre> </div>

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c#跨线程停止timer c#批量写入sql数据库 c# 自动安装浏览器 c#语言基础考试题 c# 偏移量打印是什么 c# 绘制曲线图 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行
立即提问