Passing data to server and updating asynchronously
Basically I have a site where I want the user to input something, have it go to the server for processing and then return it asynchronously, load the contents into a div and then fade it in with jQuery. What is the best way to the do accomplish this?
Currently here is my "solution":
$(document).ready(function () {
$('#output-box').hide();
$('#form1').submit(function () {
$.ajax({
type: "POST",
url: "Default.aspx/ParseData",
data: "{ $('#txtInput').val() }",
success: function (msg) {
$('#output-开发者_如何学运维box').text(msg).fadeIn();
}
});
return false;
});
});
It doesn't work - just returns the contents of Default.aspx. So how do I properly send the contents of #txtInput to the ParseData function in Default.aspx.vb? Also, is this the best way to accomplish something like this? Should I even need to use jQuery to send the data, or should I simply call the function and have it grab the data server-side, put in the information in the result div, and then show it using jQuery?
Also, I've found similar questions (and have asked a similar question myself) but I haven't been able to make it work yet..
In addition to the other suggestions, you need to set a contentType of application/json
on the request. You also need to set a dataType of json
to be sure jQuery interprets the response correctly.
$.ajax({
type: 'POST',
url: 'Default.aspx/ParseData',
data: '{ "strUserInput" : ' + $('#txtInput').val() + ' }',
dataType: 'json',
success: function (msg) {
// If ASP.NET 2.0:
$('#output-box').text(msg).fadeIn();
// If ASP.NET 3.5+:
$('#output-box').text(msg.d).fadeIn();
}
});
See this post for more info on the .d issue there: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
The server-side method should be defined like this:
[WebMethod]
public static ParseData(string strUserInput)
{
return "Message";
}
This post covers it all pretty well: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
change this
data: "{ $('#txtInput').val() }",
to
data: $('#txtInput').val(),
Looks OK to me, but you can try to change the line:
data: "{ $('#txtInput').val() }",
to
data: $('#txtInput').val(),
精彩评论