.NET syntax of responsestring to match JS-callback function with multiple parameter
i would like to pass multiple parameters in my callback function and don't know who to do this...
This would be the C# code:
Response.Clear();
Response.ContentType = "text/plain";
Response.Write("content of param1");
Response.Write("content of param2");
Response.End();
and the JS code:
$.getJSON("localhost/myFunction", dataString,
function(param1, param2) {
alert(param1);
alert(param2);
});
How would i perform the ac开发者_如何转开发tual mapping of parameter in the C# code, so JavaScript recognizes them as the 2 parameters of the callback function? ( In detail i want to pass a JSON-object and a "status" parameter here... )
There is a proper way to do this, and I'm sure you'll find it quite convenient, so I'll show you that instead of hacking away at what you've got to make it work:
Create a webservice file (asmx) in your website. In the cs (or vb) file that's created, just above the class declaration, there's a ScriptService
attribute that's commented out. Uncomment it, so that you can access the service from script.
Create a new method that returns the values in an object (anonymous types will do). Note the WebMethod
attribute:
[WebMethod]
public object MyFunction() {
return new {
status = "Status string",
jsobj = new {
childParam = "complex object",
childArray = new[] { "holds", "any", "values", "convertible", "to", "js" }
}
};
}
You can now make an AJAX call to this method, from your code, like so:
$.ajax({
type: 'POST',
url: 'MyService.asmx/MyFunction',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{}',
success: function(res) {
alert(res.status);
alert(res.jsobj.childParam);
}
});
This way, .NET will take care of the JSON serialization for you, and you won't have to worry about escaping characters within your return values etc.
Send the parameters as a JSON encoded object:
Response.ContentType = "application/json";
Response.Write("{ param1: 'value1', param2: 'value2' }");
And in javascript:
$.getJSON('localhost/myFunction', dataString,
function(json) {
alert(json.param1);
alert(json.param2);
});
精彩评论