jQuery Cross Domain Ajax

前端 未结 7 1896
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: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.

提交回复
热议问题