I am new to jQuery and I am implementing an example I found on CodeProjects.
What I need is to get a string with an imagename and new image index returned from the PageMethod I am calling. However each time I try to return something else than a number via Response.Write the callback fails and I go into the error function.
$(document).ready(function() {
var imageIndex = $("[id$='hdn_imageIndex']");
var app_path = $("[id$='hdn_app_path']");
$("#btn_next").click(function() {
var json = "{'Index':'" + imageIndex.val() + "'}";
var ajaxPage = app_path.val() + "/JSONProcessor.aspx?NextImage=1"; //this page is where data is to be retrieved and processed
var opt开发者_如何转开发ions = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=UTF-8",
dataType: "json",
async: false,
success: function(result) {
alert("success: " + result.d);
// I want my return value from my PageMethod HERE.
},
error: function(msg) { alert("failed: " + msg.d); }
};
var returnText = $.ajax(options).responseText;
});
});
The PageMethod in JSONProcessor.aspx looks like this:
public void NextImage()
{
System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
string line = "";
line = sr.ReadToEnd();
JObject jo = JObject.Parse(line);
int newImageIndex = -1;
int oldImageIndex = int.Parse(Server.UrlDecode((string)jo["Index"]));
List<string> images = (List<string>)Session["ShowHouseImages"];
int noOfImages = images.Count;
if (noOfImages > 0)
{
if (oldImageIndex == noOfImages - 1)
{
newImageIndex = 0;
}
else
{
newImageIndex = oldImageIndex + 1;
}
string[] result = ChangeImage(newImageIndex, images);
Response.StatusCode = 200;
Response.Write("1");
// What I REALLY WANT TO RETURN IS THIS
// Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
}
Response.Write("0");
}
JSON return from WebMethods does not seem to be a part of .NET 2.0. That is why I do it like this. Hope somebody can help me out.
To my understanding in the line
Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
you are not returning a correct JSON object. It should probably look something like
Response.Write(string.Format("{{images:[{0},{1},{2}]}}", result[0], result[1], result[2]));
This returns you an array with three elements. The produced output should be:
{images:[1,2,3]}
In JavaScript you can access data using result.images[0],result.images1, etc. I'm not sure if you need to specify array object name (images).
I suggest you take a look at JSON website to get a better understanding of the syntax. This way you will be able to construct complex object by yourself.
精彩评论