WCF Cross Domain Using Jsonp Error Uncaught Syntax

2019-03-07 02:41发布

I am trying to call webservice over cross domain using jQuery.

Here is my code to call service

 $(document).ready(function () {
        $.ajax({
            type: 'GET',
            async: false,
            contentType: "application/json",
            url: "http://localhost:52136/Service1.svc/Helloworld?callback=func_callbk",
            dataType: "jsonp",
            success: function (data) {
                alert('sucesss')
                alert(data.d);
            },
            error: function (data) {
                alert(data);
            }
        });
    });

    func_callback = function (data) {
        alert(data.data.people[0].id);
    }

I am returning simple string from the service.

public string HelloWorld()
{
    return "Hello World";
}

Service is called from, but I am getting error

Uncaught SyntaxError: Unexpected token :

in console window of Chrome.

I am getting this string while calling service from the browse:

{"HelloWorldResult":"Hello World"}

Please let me know where am I going wrong?

Thanks in advance.

1条回答
Summer. ? 凉城
2楼-- · 2019-03-07 03:09

Your WCF server should be configured to enable jsonp with CrossDomainScriptAccessEnabled

Here is a simple working example

Server:

Task.Run(() =>
{
    var uri = new Uri("http://0.0.0.0/test");
    var type = typeof(TestService);
    WebServiceHost host = new WebServiceHost(type, uri);
    WebHttpBinding binding = new WebHttpBinding();
    binding.CrossDomainScriptAccessEnabled = true;
    host.AddServiceEndpoint(type, binding, uri);


    host.Open();

});

[ServiceContract]
public class TestService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public string Hello()
    {
        return "Hello World";
    }
}

And this is the javascript code

<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
    $(document).ready(function () {
    $.ajax({
        type: 'GET',
        async: false,
        contentType: "application/json",
        url: "http://localhost/test/hello",
        dataType: "jsonp",
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert(data);
        }
    });
});

</script>
</body>
</html>

Now you can test it from your browser

http://localhost/test/hello

and

http://localhost/test/hello?callback=myfunc
查看更多
登录 后发表回答