简体   繁体   中英

In JQuery why one of ajax request is working while other isn't?

I am developing an application in which i have to call multiple ajax requests. I was sending $.GET and $.POST ajax requests which were working just fine but then I tried to give a shot to the common $.ajax request.The problem is that $.ajax is not working, below is piece of code

//get request with $.get works

           $.get("/RequestCont/Task2", function (data) { alert(data); });

//common ajax request below don't work


           $.ajax({
                    url: "/RequestCont/Task2",
                    type: "GET",
                    dataType: "json",
                    success:function(data)
                    {
                        //processing json data here
                    },
                    failure:function(data)
                    {
                        //handling error here
                    }

                });

I am using asp.net mvc , actual code I haven't wrote here just a piece of code to demonstrate that it works or not. This action is in the controller RequestCont

public ActionResult Task2()
    {
        if (Request.IsAjaxRequest())
        {
            return Json(new { msg = "data retrieved" });
        }
        else
        {
            return null;
        }
    }

Any thoughts on that. I want to retrieve the json data !. am I doing something wrong or what ? any one help me out !. Thanks !!.

You are sending the JSON data in the wrong format from backend.

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/ .

Source:

get json jquery reference

Check Similar SO Question

jQuery $.ajax request of dataType json will not retrieve data from PHP script

The problem was that I was missing the JsonRequestBehavior.AllowGet in the code. everything was fine. For all those experiencing the same problem at any stage note that in your json object you must always put the JsonRequestBehavior.AllowGet

modified action is below !.

public ActionResult Task2()
    {
        if (Request.IsAjaxRequest())
        {
            return Json(new { msg = "data retrieved" },JsonRequestBehavior.AllowGet);
        }
        else
        {
            return null;
        }
    }

this works for post also..

happy coding :-)

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