jQuery-AJAX calling ASP.NET page method. How to return value back to jQuery?

前端 未结 3 1474
灰色年华
灰色年华 2021-01-13 03:08

If I use jQuery AJAX to call a specific ASP.NET page method how to have that method return a value back to the AJAX method that called it?

Update

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 03:35

    With pure ASP.NET (not talking WCF here) I'd go with a handler (ASHX) file, and use JSON as the interchange format. I won't get into the details of JSON (here is a decent start), but the idea is a lightweight handler on the server that generates json text and returns it to the client, which can then use the structure easily in javascript.

    This is obviously a simplified example but the gist is the JSON can be data driven from the server and easily consumed by the javascript on the client.

    server:

    <%@ WebHandler Language="C#" Class="Handler" %>
    
    using System;
    using System.Web;
    
    public class Handler : IHttpHandler {
    
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "text/json";
            context.Response.WriteFile("~/myData.json");
        }
    
        public bool IsReusable {
            get {
                return false;
            }
        }
    }
    

    client:

    myData = 
          (function () 
           {
              var json = null;
              $.ajax({
                  'async': false,
                  'global': false,
                  'url': "handler.ashx",
                  'dataType': "json",
                  'success': function (data) {    
                      // this code is called when the 
                      // data is returned from the server              
                      json = data;
                  }
              });
              return json;    
          }
              )(); 
    
    alert(myData.MyArray[0].MyProperty);
    

提交回复
热议问题