简体   繁体   中英

Is it possible to run Ajax within a C# method? (Controller of MVC)

Maybe this is silly but I was wondering if it is possible to run any scripts, specifically Ajax, within the Controller of .Net MVC.

ie Can I wrap this in anything to make it compile and work when this method is called?

    [HttpPost]
    public ActionResult apiLookUp()
    {

     $.ajax({
        url: 'example.com/api',
        type: 'GET',
        dataType: 'json',
        data: {

        },
        success: function (json) {

        },
        error: function (errorThrown) {
            }
    });
        return Json(new { Success = json });
    }

If you are trying to access one of your own resources, then making an AJAX call is not necessary. You are already at the server, and could instantiate the object and make the call directly.

But, if your goal is to call an external site, then yes you can.

 HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://someServer.com/example.com/api");
 myReq.ContentType = "application/json; charset=utf-8";
 var response = (HttpWebResponse) myReq.GetResponse();
 string text;

 using (var sr = new StreamReader(response.GetResponseStream()))
 {
     text = sr.ReadToEnd();
 }

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