简体   繁体   中英

Consuming WebService in Cross Domain

It should be very simple. I have read a lot of posts about consuming web service cross domain and the use of JSONP, but there is something I am missing.

If I call the following URL in the WebBrowser, I can get my result: http://benfaniz.com.br/WebService.asmx/AAA_Buscar_Nome_Condominio?callback=?

To consume it using jQuery, I am using:

    $(document).ready(function() {
        var surl = "http://benfaniz.com.br/webservice.asmx/AAA_Buscar_Nome_Condominio";
        $.ajax({
            type: 'POST',
            url: surl,
            dataType: "jsonp",
            success: function(msg) {
                alert(msg.data);
            },
            error: function(xhr, status, error) { 
                alert("error"); 
            }
        });
    });

Here is the JS Fiddle

But I keep getting error? What is the problem?


UPDATE

I can get the content of the URL using the following code (taken from here )

    $(document).ready(function() {


        var theUrl = "http://benfaniz.com.br/WebService.asmx/AAA_Buscar_Nome_Condominio?callback=?"            

            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    alert(xmlhttp.responseText);
                }
            }
            xmlhttp.open("GET", theUrl, false );
            xmlhttp.send();    


    });

Please, look at JS Fiddle

I could do it. I found this question here that gave me the directions.

The main problem is that I was getting a XML result instead of JSON. To change this, I had to add the line contentType: "application/json; charset=utf-8" .

The final code is the following:

$(document).ready(function() {
    var surl = "http://benfaniz.com.br/webservice.asmx/AAA_Buscar_Nome_Condominio";
    $.ajax({
        url: surl,
        contentType: "application/json",
        dataType: "json",
        success: function (json) {
            alert(json.d);
        },
        error: function (xhr) {
            alert("ERRO");
        }
    }); 
});

JS Fiddle

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