简体   繁体   中英

Calling WCF Service from JavaScript using AJAX through JQuery

I'm trying to call a WCF Service located locally through JavaScript. Here is a sample of the WCF Service.

public string GetMarkers()
    {
        List<Marker> lstMarkers = new MarkerMgr().GetMarkers().ToList();
        List<Marker> lstMark = new List<Marker>();
        foreach (Marker m in lstMarkers)
        {
            Marker marker = new Web_Service.Marker();
            marker.Id = m.Id;
            marker.Latitude = m.Latitude;
            marker.Longitude = m.Longitude;
            marker.Title = m.Title;
            marker.Description = m.Description;
            marker.Icon = m.Icon;
            lstMark.Add(marker);
        }

        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.MaxJsonLength = Int32.MaxValue;

        return jss.Serialize(lstMark);
    }

and this is the function which I'm using to call the WCF Service.

function getMarkers() {
        var markers = null;
        $.ajax({
            async: true,
            type: "GET",
            url: "http://localhost:61892/Service.svc/GetMarkers", // the URL of the controller action method
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: true,
            success: function (result) {
                alert(result);
                markers = result;
            },
            error: function (req, status, error) {
                alert(error);
            }
        });
        return markers;
    }

I've tried many different approaches to solve this but they weren't successful. From all the research I've done I think its something about the localhost. Anyone has an idea? Thanks a lot.

You are trying for a cross domain ajax. So there shold enable cors in your ajax calling page. And also server should make

"Access-Control-Allow-Origin" header to "*"

take a look at this

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