简体   繁体   中英

Calling ASP.NET page from a JS and sending Response

I have a JS script:

  $.ajax({
        type: "GET",
        url: ServiceAddress + "/Service.aspx?action=LoadRandomImagePath&userID=" + USER_ID,
        success: function (result) {
            if (result.LoadRandomImagePathResult.ID != 0) {
        //something
        }

When Service.aspx is called:

Response.Write(svc.LoadRandomImagePath(int.Parse(Request.QueryString["userID"])));

svc.LoadRandomImagePath returns JSON and writes it to Response.

My problem is following. Result on JS side is a full code of Service.aspx:

{JSON HERE}  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title> </title></head> <body> <form method="post" action="Service.aspx?action=LoadRandomImagePath&amp;userID=18" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZLyq7A39QtHu0Ngft6E/6ZwTABk29noGDsoP6FKK6UIo" /> </div> <div> </div> </form> </body> </html>

but what I want is only JSON response, without code of the page. How can I do that? Is it possible?

Have you tried specifying the return data type as a JSON in your initial request?

 $.ajax({
        type: "GET",
        dataType: "json",
        url: ServiceAddress + "/Service.aspx?action=LoadRandomImagePath&userID=" + USER_ID,
        success: function (result) {
            if (result.LoadRandomImagePathResult.ID != 0) {
        //something
 }

Additionally you will want to clear anything written already and change the data type for the JSON page:

Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(svc.LoadRandomImagePath(int.Parse(Request.QueryString["userID"])));
Response.End();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM