jQuery Cross Domain Ajax

前端 未结 7 1897
Happy的楠姐
Happy的楠姐 2020-12-09 05:06

My ajax code is

$.ajax({
    type: \'GET\',
    dataType: \"jsonp\",
    processData: false,
    crossDomain: true,
    jsonp: false,
    url: \"http://someo         


        
相关标签:
7条回答
  • 2020-12-09 05:23

    You just have to parse the string using JSON.parse like this :

    var json_result = {"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"};
    
    var parsed = JSON.parse(json_result.AuthenticateUserResult);
    console.log(parsed);
    

    Here you will have something like this :

    Designation
    null
    
    FirstName
    "Miqdad"
    
    LastName
    "Kumar"
    
    PKPersonId
    1234
    
    PhotoPath
    "/UploadFiles/"
    
    Profile
    ""
    
    Salutation
    null
    

    And for the request, don't forget to set dataType:'jsonp' and to add a file in the root directory of your site called crossdomain.xml and containing :

    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
    <!-- Read this: www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
    
    <!-- Most restrictive policy: -->
    <site-control permitted-cross-domain-policies="none"/>
    
    <!-- Least restrictive policy: -->
    <!--
    <site-control permitted-cross-domain-policies="all"/>
    <allow-access-from domain="*" to-ports="*" secure="false"/>
    <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
    -->
    </cross-domain-policy>
    

    EDIT to take care of Sanjay Kumar POST

    So you can set the callback function to be called in the JSONP using jsonpCallback!

    $.Ajax({
        jsonpCallback : 'your_function_name',
        //OR with anonymous function
        jsonpCallback : function(data) {
            //do stuff
        },
        ...
    });
    
    0 讨论(0)
  • 2020-12-09 05:24

    Looks like the inner JSON struct is passed along as a string. You'll have to JSON.parse() it once more to get that data as an object.

    try {
      responseData = JSON.parse(responseData);
    }
    catch (e) {}
    

    Edit: Try the following:

    $.ajax({
        type: 'GET',
        dataType: "json",
        url: "http://someotherdomain.com/service.svc",
        success: function (responseData, textStatus, jqXHR) {
            console.log("in");
            var data = JSON.parse(responseData['AuthenticateUserResult']);
            console.log(data);
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.');
        }
    });
    
    0 讨论(0)
  • 2020-12-09 05:24

    If you are planning to use JSONP you can use getJSON which made for that. jQuery has helper methods for JSONP.

    $.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {
           console.log(result);
    });
    

    Read the below links

    http://api.jquery.com/jQuery.getJSON/

    Basic example of using .ajax() with JSONP?

    Basic how-to for cross domain jsonp

    0 讨论(0)
  • 2020-12-09 05:32

    Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

    $.ajax({
        type: 'GET',
        dataType: "text",
        crossDomain: true,
        url: "http://someotherdomain.com/service.svc",
        success: function (responseData, textStatus, jqXHR) {
            var authResult = JSON.parse(
                responseData.replace(
                    '{"AuthenticateUserResult":"', ''
                ).replace('}"}', '}')
            );
            console.log("in");
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.');
        }
    });
    

    It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

    Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

    0 讨论(0)
  • 2020-12-09 05:38

    The response from server is JSON String format. If the set dataType as 'json' jquery will attempt to use it directly. You need to set dataType as 'text' and then parse it manually.

    $.ajax({
        type: 'GET',
        dataType: "text", // You need to use dataType text else it will try to parse it.
        url: "http://someotherdomain.com/service.svc",
        success: function (responseData, textStatus, jqXHR) {
            console.log("in");
            var data = JSON.parse(responseData['AuthenticateUserResult']);
            console.log(data);
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.');
        }
    });
    
    0 讨论(0)
  • 2020-12-09 05:41

    Here is the snippets from my code.. If it solves your problems..

    Client Code :

    Set jsonpCallBack : 'photos' and dataType:'jsonp'

     $('document').ready(function() {
                var pm_url = 'http://localhost:8080/diztal/rest/login/test_cor?sessionKey=4324234';
                $.ajax({
                    crossDomain: true,
                    url: pm_url,
                    type: 'GET',
                    dataType: 'jsonp',
                    jsonpCallback: 'photos'
                });
            });
            function photos (data) {
                alert(data);
                $("#twitter_followers").html(data.responseCode);
            };
    

    Server Side Code (Using Rest Easy)

    @Path("/test_cor")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String testCOR(@QueryParam("sessionKey") String sessionKey, @Context HttpServletRequest httpRequest) {
        ResponseJSON<LoginResponse> resp = new ResponseJSON<LoginResponse>();
        resp.setResponseCode(sessionKey);
        resp.setResponseText("Wrong Passcode");
        resp.setResponseTypeClass("Login");
        Gson gson = new Gson();
        return "photos("+gson.toJson(resp)+")"; // CHECK_THIS_LINE
    }
    
    0 讨论(0)
提交回复
热议问题