0.html:
<input id="btn" type="button" value="ajax json" />
<input id="btn2" type="button" value="ajax content" />
<input id="txt4" type="text" value="456" />
<input id="txt1" type="text" value="123" />
<input id="txt2" type="text" value="234" />
<input id="txt3" type="text" value="345" />
1.使用json数据形式
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
type: 'POST',
url: "/Student/MyAjax",
data: {
val1: $("#txt1").val(),
val2: $("#txt2").val(),
val3: $("#txt3").val(),
val4: $("#txt4").val()
},
success: function (obj) { alert(obj["stuNo"] + "," + obj["classId"] + "," + obj["name"]);},
dataType: "json"
});
});
});
[HttpPost]//记得要加HTTPPOST标记!
public JsonResult MyAjax(FormCollection f)
{
string val1 = f["val1"].ToString();
string val2 = f["val2"].ToString();
string val3 = f["val3"].ToString();
string val4 = f["val4"].ToString();
Student s = new Student()
{
stuNo = val1,
classId = val2,
name = val3
};
return Json(s);
}
2.直接传字符串:
$("#btn2").click(function () {
$.ajax({
type: 'POST',
url: "/Student/MyAjax2",
data: "val1=" + $("#txt1").val() + "&val2=" + $("#txt2").val() +
"&val3=" + $("#txt3").val() + "&val4=" + $("#txt4").val(),
success: function (obj) { alert(obj); }
});
});
[HttpPost]
public ContentResult MyAjax2(FormCollection f)
{
string val1 = f["val1"].ToString();
string val2 = f["val2"].ToString();
string val3 = f["val3"].ToString();
string val4 = f["val4"].ToString();
string s = "";
s += val1 + ",";
s += val2 + ",";
s += val3 + ",";
s += val4 ;
return Content(s);
}