cross domain call with jQuery jsonp to ASP.NET web service

前端 未结 1 998
南方客
南方客 2021-01-05 23:01

My problem is known issue and discussed here and here. But even after reading and implementing the suggested solutions i am unable to make this work.

The pro

相关标签:
1条回答
  • 2021-01-05 23:38

    It seems all the configuration and attributes are in place for the web service to return JSON but I did notice in your jQuery request, you are not specifying the content type of the data you are passing in. I have added it to the code below:

    $.ajax({
      url: "http://tonofweb.com/MyService.asmx/Sum",
      contentType: "application/json; charset=utf-8",
      data: { x: JSON.stringify("1"), y: JSON.stringify("2") },
      dataType: "jsonp",
      success: function (json) {
        alert(json.d);
      },
      error: function () {
        alert("Hit error fn!");
      }
    });
    

    Notice I added contentType: "application/json; charset=utf-8", to the request settings.

    I have tested this code by browsing to http://tonofweb.com (which returns a 403 at the moment), including jQuery using the jQuerify bookmarklet, and then running the code from your question first (without the contentType), and then the code I posted above (with the contentType).

    Here are the responses from the Network tab in the Chrome Developer Tools:

    Without contentType:

    <?xml version="1.0" encoding="utf-8"?>
    <string xmlns="http://tempuri.org/">"Now i am getting jsop string""2nd param"</string>
    

    With contentType:

    {"d":"12"}
    

    So the second one at least results in JSON being returned from the server. So all else being equal, I'd say add the contentType.

    See here for an explanation of the requirements to return JSON:

    ASMX and JSON – Common mistakes and misconceptions

    The HTTP request must declare a content-type of application/json. This informs the ScriptService that it will receive its parameters as JSON and that it should respond in kind.

    Now you still have another problem, and that is that the request, upon completion, calls the error function. If you change dataType: "jsonp" to dataType: "json" it will call the success function. So something about your implementation of the callback wrapper is wrong, because jQuery can't handle the response as JSONP.

    Now I'm not seeing the callback wrapped in the response either, for JSONP, the response should be something like:

    jQuery17106476630216930062_1326752446188({"d":"12"})
    

    I notice you are linking to this post about how to do a JSONP response from a web service, but you are not following the advice: you don't use Response.Filter, instead you use Response.Write.

    0 讨论(0)
提交回复
热议问题