jquery ajax怎么通过header传递参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jquery ajax怎么通过header传递参数相关的知识,希望对你有一定的参考价值。
首先的首先,涉及业务逻辑的输入是需要通过参数传递的,主要有三种方法:path, query, POST/PUT bodypath: GET /api/user/123 其中的123通过path传递
query: GET /api/search_user?userId=123
body: POST /api/user-signup username: \'john\'
不建议通过header传参的原因:
1. proxy 和 reverse proxy会drop header
2. 不利于传输object
3. HTTP access control (CORS) API 一般会设置Access-Control-Allow-Headers,分分钟教你做人。
4. 不利于dev和debug
5. Header长度限制
然后,如果你需要传header,比如Authorization,如下。
jQuery.ajax()
headers (default: )
Type: PlainObject
An
object of additional header key/value pairs to send along with requests
using the XMLHttpRequest transport. The header X-Requested-With:
XMLHttpRequest is always added, but its default XMLHttpRequest value can
be changed here. Values in the headers setting can also be overwritten
from within the beforeSend function. (version added: 1.5)$.ajax(
url: \'/path/to/service\',
method: \'GET | POST | PUT | DELETE\',
headers:
\'Authorization\': \'Bearer <jwt token>\',
\'some-other-header\': \'some value\'
)
.done(function(data)...)
.fail(function(jqXHR)...)
.always(function()...) 参考技术A 参数啊, ajax 有个 data: 名字1: "值", 名字2: 值2
JQuery.Ajax()的data参数传递方式
最近,新学c# mvc,通过ajax post方式传递数据到controller。刚开始传递参数,controller中总是为null。现记录一下,可能不全,纯粹记个学习日记。
重点在于参数的方式,代码为例子
1、这里 dataType: "json",表示返回的格式是json
前端:
var saveAlbum = function () { $.ajax( { url: "/Home/PostAlbum", type: "POST", dataType: "json", data: { AlbumName: "shanghai", Entered: "5/9/2013" }, success: function (result) { alert(result); }, error: function (xhr, status, p3, p4) { var err = "Error " + " " + status + " " + p3; if (xhr.responseText && xhr.responseText[0] == "{") err = JSON.parse(xhr.responseText).message; alert(err); } }); }
controller:
public ActionResult PostAlbum(test test) { string str = String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered); return Json(str);//--------对应请求中dataType: "json",表示需要返回json类型 //return String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered);//------如果是string,则会报错 }
2、ajax请求中还要一个重要的参数: contentType: "application/json",表示传入参数的格式
var saveAlbumJson = function () { $.ajax( { url: "/Home/PostAlbum", type: "POST", contentType: "application/json", dataType:"json", data: JSON.stringify({ "AlbumName": "shanghai", "Entered": "5/9/2013" }), success: function (result) { alert(result); }, error: function (xhr, status, p3, p4) { var err = "Error " + " " + status + " " + p3; if (xhr.responseText && xhr.responseText[0] == "{") err = JSON.parse(xhr.responseText).message; alert(err); } }); }
[HttpPost] public ActionResult PostAlbum(test test) { string str = String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered);//传入test实体 return Json(str); //return String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered); }
public class test { public string AlbumName { get; set; } public DateTime Entered { get; set; } }
3、如果要传入list<实体>,比如List<test>,需要把传入的data做转换
var saveAlbumJsonList = function () { $.ajax( { url: "/Home/AlbumList", type: "POST", contentType: "application/json", dataType: "json", data: JSON.stringify({"input":[{ AlbumName: "shanghai", Entered: "5/9/2013" },{...},{....}]}), success: function (result) { alert(result); }, error: function (xhr, status, p3, p4) { var err = "Error " + " " + status + " " + p3; if (xhr.responseText && xhr.responseText[0] == "{") err = JSON.parse(xhr.responseText).message; alert(err); } }); }
public ActionResult PostAlbumList(List<test> input)//input必须要与data中数组中的key匹配 { if (input != null) { string str = String.Format("保存成功PostAlbum:{0} {1:d}", input[0].AlbumName, input[0].Entered); return Json(str); }else { return Json("参数获取错误!"); } //return String.Format("保存成功PostAlbum:{0} {1:d}", test.AlbumName, test.Entered); }
4、由上面三个例子,很容易想到,传入多个list<实体>的方式
function postEmployees() { $.ajax({ type: "POST", url: "/Home/Employees", contentType: "application/json", dataType: "json", async: false, data: JSON.stringify({ "Employees": [{ "Id": "1", "lastName": "Gates" }, { "Id": "2", "lastName": "Bush" }, { "Id": "3", "lastName": "Carter" }], "Employers": [{ "Id": "4", "lastName": "Gates" }, { "Id": "5", "lastName": "Bush" }, { "Id": "6", "lastName": "Carter" }] }), success: function (jsonResult) { alert(jsonResult); } }); }
[HttpPost] public async Task<ActionResult> Employees(List<Employee> Employees, List<Employee> Employers) { return Json("Employees", JsonRequestBehavior.AllowGet); }
public class Employee { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
以上是关于jquery ajax怎么通过header传递参数的主要内容,如果未能解决你的问题,请参考以下文章