Strange jQuery $ .Ajax () behavior using JSONP data type: how to fix?

This is a working JSON request:

$.ajax({
    type: "POST",
    url:  "GetJSON",
    data: {},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (j) {
        myFunctionName(j);
    }
});

And another almost identical JSONP request, which also works:

$.ajax({
    type: "GET",
    url:  "GetJSONP",
    data: {},
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    success: function (j) {
        myFunctionName(j);
    }
});

Now, if you change success: for jsonpCallback: on the second request, it calls the myFunctionName function twice. The result of the server is myFunctionName ([jsondata]), where [jsondata] is json-encoded data.

$.ajax({
    type: "GET",
    url:  "GetJSONP",
    data: {},
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    jsonpCallback: "myFunctionName"
});

What am I doing wrong in the third code example that calls myFunctionName twice?

Answer:

In ASP.NET MVC 3, I used this:

public class JsonpResult : ActionResult
{
    public override void ExecuteResult( ControllerContext c)
}

And this:

public static JsonpResult Jsonp(this Controller c, object d)
{    
    JsonpResult r = new JsonpResult();
    r.Data = d;
    // r.ExecuteResult(c.ControllerContext);  <== mistake
    return r;
}

And this:

public JsonpResult GetJSONP()
{
    var service = new Service();
    var data = service.Getdata();
    return this.Jsonp(data);
}

The error was noted in the comments. Apparently ASP.NET MVC calls ExecuteResult for you, so calling it manually adds data twice to the result.

+3
source share
1 answer

:

, JSONP myFunctionName ?

+2

Source: https://habr.com/ru/post/1787977/


All Articles