1、Json转字符串,字符串转Json
//Json转字符串
alert(JSON.stringify(result));
//字符串转Json
var obj = jQuery.parseJSON('{"name":"John"}');
alert(obj.name);
//字符串转Json(JavaScript原生)
var arr1 = eval('({"name":"John"})');
console.log(arr1.name);
2、success -> contentType: "application/json"
$.ajax({
type: "post",
url: '@Url.Action("GetCity", "Default")',
contentType: "application/json",
dataType: "json",
data: {
"provinceId": $("#Provinces").val()
},
success: function (result) {
var html = "";
$(result.Data).each(function (index, item) {
html += "<option value='" + item.Id + "'>" + item.Title + "</option>";
});
$("#Citys").html(html);
}
});
3、done -> contentType: "application/x-www-form-urlencoded"
$.ajax({
type: 'post',
url: '/Asset/SaveIsCommon',
contentType: "application/x-www-form-urlencoded",
dataType: "json",
data: {
"Id": id,
"IsCommon": $("#hidId").val(),
},
}).done(function (result) {
if (result.Success) {
} else {
showError(result.ErrorMessage, dialogCopy);
}
});
4、done -> contentType: "application/json" -> [FromBody]LoginRequest request【415Unsupported Media Type,data参数添加 JSON.stringify】
$("#btnLogin").click(function () {
$.ajax({
type: 'post',
url: '/Login',
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({
"username": $("#username").val(),
"password": $("#password").val()
}),
}).done(function (res) {
//window.location.href = 'http://localhost:9527/#/token=123456'
$(location).attr("href", "http://localhost:9527/#/token=123456");
console.log(123)
});
});
5、跨域访问【注意:只支持get请求,不支持post请求】
● JQuery对于Ajax的跨域请求有两类解决方案,都是只支持get方式。分别是JQuery的 ajax jsonp格式和jquery.getScript方式。
● 要使用跨源请求发送凭据,客户端必须设置为:withCredentials: true
● 后端需要添加一个解决跨域方位的过滤器
API接口
[HttpGet("LoginJsonp")]
public IActionResult LoginJsonp()
{
return Ok("callback(" + JsonConvert.SerializeObject(new { code = "200" }) + ")");
}
[HttpGet("GetTicket")]
public IActionResult GetTicket()
{
HttpContext.Response.Cookies.Append("password", "123456");
HttpContext.Response.Cookies.Append("time", "abcd");
return Ok("callback(" + JsonConvert.SerializeObject(new { code = "200", data = new { ticket = "1234567890abcd" } }) + ")");
}
[HttpGet("GetTicketNew")]
public IActionResult GetTicketNew()
{
return Content("jsonpscall(" + JsonConvert.SerializeObject(new { code = "200", data = new { ticket = "1234567890abcd" } }) + ")");
}
跨域 ajax 代码
//待测试
$.ajax({
type: 'post',
url: 'http://www.wufawutianpk.com/api/User/Login',
headers: {
"Token": "3031b6b9-41fb-420a-b125-0aaa89e0832a"
},
dataType: "jsonp",
jsonp: "jsoncallback",
jsonpCallback:"flightHandler",
xhrFields: {
withCredentials: true
}
data: {
"Telephone": "15131468178",
"Password": "111111"
}
}).done(function (result) {
console.log(JSON.stringify(result.Data));
});
//待测试
$.ajax({
type : 'get',
url:'http://b.com/login.php',
data : {
uid : '333333',
password : '858888',
},
cache :false,
jsonp: "callback",
jsonpCallback:"success",
dataType : 'jsonp',
success:function(data){
//alert(data);
},
error:function(data){
//alert('error');
}
});
//经测试可以使用 ok
$.ajax({
url: 'http://localhost:61953/LoginJsonp',
type: 'get',
dataType: 'jsonp',
xhrFields: {
withCredentials: true
}
}).done(function (data) {
console.log("Ln 85" + data);
});
//经测试可以使用 ok
$.ajax({
type: 'get',
url: 'http://sso.com:8021/GetTicketNew',
contentType: "application/json",
dataType: 'jsonp',
jsonpCallback: "jsonpscall",
success: function (jsons) {
console.info(jsons)
},
error: function () {
alert('fail')
}
});
//ok
//$.ajax({
// type: 'get',
// //url: 'http://localhost:61206/LoginAsync',
// //url: 'http://sso.com:8021/LoginJsonp',
// url: 'http://sso.com:8021/GetTicket',
// contentType: "application/json",
// dataType: 'jsonp',
// data: {
// Id: 1,
// IsCommon: 1,
// },
//}).done(function (res) {
// if (res.ticket) {
// console.log('/get-user-info?ticket=' + data.ticket);
// }
// console.log(res)
//});
//ok
var ssoBaseUrl = 'http://sso.com:8021';
//var ssoBaseUrl = 'http://localhost:61206';
//console.log("123abcd")
//$.getJSON(ssoBaseUrl + '/GetTicket?callback=?').then(function(data) {
// if (data.ticket) {
// console.log("Ln 75" + data.ticket);
// }
// location.href = ssoBaseUrl + '/login?redirect=' + redirect;
//}).then(function(result) {
// if (result.code != 0) {
// return alert(result.msg || '逻辑错误');
// }
// location.href = '/user-backend';
//}).fail(function() {
// alert('网络错误');
//});
//回调函数方法(默认方法名称是“callback”)
function callback(data) {
//$.each(data.success, function (i, item) {
// $("body").append('<h1>' + item.title + '</h1>');
//});
console.log(JSON.stringify(data));
}
function jsonpCallback(result){
alert(result.msg);
}
6、jQuery each 循环
//推荐使用此方法
$(arrayJson).each(function (index, item) {
if (id == item.Id) {
assetJson.splice(index, 1);
return;
}
});
//在某次使用中,莫名其妙的报错了,提示“Cannot read property 'Id' of undefined”
$.each(assetJson, function (index, item) {
if (id == item.Id) {
assetJson.splice(index, 1);
return;
}
});
*
*
*