[英]Making ajax calls using $.ajax in ASP.NET Web Forms
I am trying to use $.ajax
method in my example program. 我试图在示例程序中使用
$.ajax
方法。 I have designed the page like below: 我设计了如下页面:
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />
<div id="container"></div>
</div>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
debugger;
var data = {};
data.country = $("#txtCountry").val();
data.title = $("#txtTitle").val();
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + status);
}
</script>
</form>
Code inside PostTarget.aspx.cs is defined below. 下面定义了PostTarget.aspx.cs中的代码。
protected void Page_Load(object sender, EventArgs e)
{
var country = Request.Form["country"];
var title = Request.Form["title"];
var db = new NORTHWNDEntities();
var emps = db.Employees
.Where(x => x.Country.Contains(country) || x.Title.Contains(title))
.Select(x => new EmployeeSearchResult
{
EmployeeID = x.EmployeeID,
FirstName = x.FirstName,
LastName = x.LastName
});
Response.Clear();
Response.Write(JsonConvert.SerializeObject(emps));
Response.Flush();
Response.End();
}
When debugging the above, I am not getting values into country
, and title
variables. 在调试上述内容时,我没有将值输入
country
和title
变量。
Verified some online resources, but code is almost similar. 验证了一些在线资源,但是代码几乎相似。
Can anyone please check and suggest me if I am doing wrong anywhere? 任何人都可以检查并建议我是否在任何地方做错了吗?
You are not sending the data correctly. 您没有正确发送数据。 For the 'x-www-form-urlencoded' type the string should be in the format:
对于“ x-www-form-urlencoded”,该字符串应采用以下格式:
country=countryName&title=titleName
As it is not, the Request.Form method is not being given the data in the format it expects. 事实并非如此,没有以其期望的格式为Request.Form方法提供数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.