[英]Return data to jquery/ajax call from entity framework object in asp.net
[英]getting jQuery Ajax return data in Asp.Net
我是jQuery的新手,不了解jQuery Ajax如何返回數據。 我有一些簡單的功能來獲取如下數據
[WebMethod(EnableSession = false)]
protected int SignIn()
{
return 0;
}
在我的.aspx頁面中,我有這個
$(document).ready(function () {
$("#si").click(function
() {
$.ajax({
type: "POST",
url: "SignIn.aspx/SignIn",
contentType: "application/json",
success: function (txt) {
alert(txt);
}
});
});
});
但在警報中,我得到了整個SignIn.aspx(所有html標記等)。 如何提醒SignIn()返回的0?
將SignIn
方法設為靜態和公共,並使用以下代碼顯示警報: alert(txt.d);
試試這個樣本。 我已經將id從aspx傳遞給了處理程序,並剛剛從那里返回以再次將服務器端數據顯示給aspx
這是示例示例.....
處理程序代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProject
{
/// <summary>
/// Summary description for TestHandler1
/// </summary>
public class TestHandler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string id = context.Request["id"];
context.Response.ContentType = "text/plain";
context.Response.Write(id);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
和aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
</form>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'TestHandler.ashx?id='+ 1,
data: 'id=' + 1,
success: function (msg) {
alert(msg);
}
});
});
</script>
</body>
</html>
您正在向ASPX文件索取數據,我認為應該是ASMX。
查閱Dave Ward的文章,我在其中了解了所有這些信息: http : //encosia.com/asp-net-web-services-mistake-manual-json-serialization/
我可以做的最簡單的示例如下所示:
添加包含以下內容的Web服務(ASMX)
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public int Status(int input) {
return input + 1;
}
}
然后在您的HTML中
<html>
<head>
<title>Test</title>
<script src="jquery-1.6.2.min.js" ></script>
</head>
<body>
<script>
$(function () {
$.ajax({
url: 'WebService.asmx/Status',
data: '{ input: 0 }',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
success: function (data, status) {
alert(data);
alert(typeof data);
}
});
});
</script>
</body>
</html>
在ajax調用中,data中定義的字符串是web方法的輸入。 名稱必須匹配。 在成功回調中,第一個警報顯示返回的值(輸入加一個),第二個警報顯示它是一個數字,而不是字符串。 由於數據類型設置為JSON,因此Web方法返回JSON,從而可以正確鍵入數據。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.