Jquery unable to get the response from WCF REST service

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 03:29:13

问题


I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".

I want to get that data using jQuery. I tried my best to get WCf get response using jQuery but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?

The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation

You can check that url response by pasting url in browser.


回答1:


You need to set Access-Control-Allow-Origin to value [*] in your response header.

this blog gives the more details how it can be done in WCF REST service

if you were to do this in Web API you could have just added

 Response.Headers.Add("Access-Control-Allow-Origin", "*")

calling the service using a fiddle

$(function() {

    $.ajax({
        url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
        datatype: 'json',
        type : 'get',
        success: function(data) {
            debugger;

            var obj = data;
        }

    });

})​;​

I got the error

XMLHttpRequest cannot load http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.




回答2:


I can't make a cross domain example to show you but

$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​

would work had those things been set.

Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.




回答3:


Sample code below:

$.ajax
(
    {
        type: 'GET',
        url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
        cache: false,
        async: true,
        dataType: 'json',
        success: function (response, type, xhr)
        {
            window.alert(response);
        },
        error: function (xhr)
        {
            window.alert('error: ' + xhr.statusText);
        }
    }
);


来源:https://stackoverflow.com/questions/14073929/jquery-unable-to-get-the-response-from-wcf-rest-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!