javascript - Redirect to WebForm with JSON -
i have situation dont want use querystrings pass data redirect page.
current implementation, source page:
window.location = "invaliduser.aspx?u=" + encodeuri(username);
i looking @ using ajax methodology not sure redirect page.
landing page:
<%@ page language="c#" autoeventwireup="true" codebehind="invaliduser.aspx.cs" inherits="itask.organizer.invaliduser" %> <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>invalid user</title> <script type="text/javascript" src="scripts/jquery-2.1.0.js"></script> <script src="scripts/app.utility.js"></script> <script src="scripts/invaliduser.js"></script> </head> <body> <h1>invalid user account:</h1> <p>your user account ( <span id="pusername"></span> ) not setup application.</p> <p>please contact <a href="mailto:email@domain.com">email recipient</a> further assistance.</p> </body> </html>
current jquery:
jquery(function ($) { $(document).ready(function () { var username = decodeuri(geturlvars().u); $("#pusername").text(username); }); });
was going ajax post method pass json data page unsure if stick on round trip, need pass data page (without using querystring), ideally in same request redirect packaged json data.
theoretical ajax/json post:
postjsonutf8( 'invaliduser.aspx', { data: username }, function (resp) { window.location = "invaliduser.aspx"; } ); function postjsonutf8(url, data, success) { postapi('json', 'application/json;charset=utf-8', url, data, success); } function postapi(type, contenttype, url, data, success) { if (typeof (success) === 'function') { $.ajax({ type: "post", contenttype: contenttype, datatype: type, url: url, data: data, success: success, error: ajaxfail }); } }
you right can't normal redirects (301/302 status codes) ajax. setup following in ajax response handling logic:
function tryhandleresponseredirect(resp, data) { if (resp.status == 200 && data && data.redirect) { // force hard re-direct window.location.href = data.redirect; return true; } }
which can handle wiring jquery's ajaxsuccess
function:
$( document ).ajaxsuccess(function( event, xhr, settings, data ) { tryhandleresponseredirect(xhr, data); });
and following on server-side in place can process outgoing http responses:
public override void onresultexecuted(resultexecutedcontext filtercontext) { var req = filtercontext.httpcontext.request; var resp = filtercontext.httpcontext.response; var shouldprocess = (resp.isrequestbeingredirected && req.isajaxrequest()); if (!shouldprocess) { base.onresultexecuted(filtercontext); return; } var location = resp.redirectlocation ?? resp.headers["location"]; var json = jsonconvert.serializeobject(new { redirect = location }); resp.clearcontent(); resp.headers.remove("location"); // send json object indicating redirect resp.statuscode = 200; resp.write(json); }
Comments
Post a Comment