[英]ajax parameter is always null?
I am trying to pass the a string to my behind code, but its always null. 我正在尝试将字符串传递给我的背后代码,但始终为null。
$.ajax({
type: "POST",
url: "Search.aspx?do=SearchText",
data: {searchText: searchText },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnsuccesscallback,
error: fnerrorcallback
});
protected void Page_Load(object sender, EventArgs e)
{
if (Request["do"] != null && Request["do"] == "SearchText")
{
string result = Search.searchText(Request["searchText"]);
}
}
My Request["searchText"] is always null. 我的Request [“ searchText”]始终为null。
EDIT: 编辑:
public void DoSearch(string SearchText)
{
string result = Search.searchText(SearchText);
}
and in the ajax post: 并在ajax帖子中:
url: "Search.aspx/DoSearch",
data: { searchText: searchText },
The problem with this is you are trying to grab the querystring within the Page_Load event which fires before the ajax code. 这样做的问题是,您试图获取Page_Load事件中的查询字符串,该事件在Ajax代码之前触发。 So on Page_Load there is no parameter passed at that stage which is why it will always be null. 因此,在Page_Load上没有在该阶段传递参数,这就是为什么它将始终为null的原因。
Ok I have set up a basic test which works for me. 好的,我已经建立了一个对我有用的基本测试。
var myString = 'Test';
$.ajax({
type: "POST",
url: "SearchTest.aspx/DoSearch",
data: '{"searchText":"' + myString + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnsuccesscallback,
error: fnerrorcallback
});
function fnsuccesscallback() {
}
function fnerrorcallback() {
}
//Remember the webmethod goes into the code behind of the SearchTest.aspx
page //记住web方法进入了SearchTest.aspx
页面后面的代码
[WebMethod]
public static void DoSearch(String searchText)
{
//Do your stuff!!
}
Remember to import the namespace... using System.Web.Services;
记住要导入名称空间... using System.Web.Services;
Hope this works for you 希望这对你有用
Try calling it as a static webmethod, passing the parameter directly into the called method. 尝试将其作为静态网络方法调用,将参数直接传递给被调用的方法。
url: "Search.aspx/DoSearch",
data: '{"searchText":"' + searchText + '"}',
//Add this on code behind page...
using System.Web.Services;
[WebMethod]
public static void DoSearch(String searchText)
{
//Do your stuff!!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.