Domanda

I'm trying to call an OData service using JQuery $.ajax and running into some issues.

When I call the service with dataType: "jsonp", I get a status code of 200 and the data I need but it falls into my JQuery error: function(data)

When I call the service with dataType: "json", I get nothing, the call to the service does not even happen.

Here is my .ajax call:
$.ajax({ beforeSend: function(request) { request.setRequestHeader("Accept", "application/json;charset=utf-8"); }, type: "GET", url: this.uri + filter, dataType: "jsonp", success: function(data) { // I never get here but in fiddler I get a 200 status code }, error: function(data) { // This works and gives me the data but it's in the JQuery error handler // $.parseJSON(data.responseText) } });
I've tried several variations "jsonp: false", "callback", etc and without success. I should also mention that the website and odata webapi are on the same server but the website is accessed via https and then the client ajax calls the service via http.

Would anyone be able to tell me where I'm going wrong?

Thanks in advance!

È stato utile?

Soluzione 2

After countless hours of effort I finally got it to work by skipping JQuery and using xmlhttprequest object, here's my working code:

var uri = this.uri + filter;

var http_request = new XMLHttpRequest();
http_request.setRequestHeader("Authorization", "Negotiate");

http_request.onreadystatechange  = function() {
    if (http_request.readyState == 4  ) {
        var data = JSON.parse(http_request.responseText);
        alert(data.value[0].Name);
    }
}

http_request.open("GET", uri, true);
http_request.send();    

I borrowed pieces from everywhere on the web so others deserve the credit.

This is for use on a local intranet running IE only, if anyone has another suggestion I can try or a better way of doing this I would appreciate your feedback.

Thanks!

Altri suggerimenti

It's very possible that you are calling an OData service that has already supported CORS. Which means that you don't need to specify to use JSONP in your request. If the response with the status code 200 that you get have a header "Access-Control-Allow-Origin: xxx", you are probably talking to this kind of service.

Try simply use the following ajax call:

$.ajax({
        type: "get",
        async: false,
        url: "http://services.odata.org/V4/OData/OData.svc/Products",
        success: function (data) {
            alert(JSON.stringify(data));
        },
        error: function (xhr, textStatus, errorMessage) {
            alert(errorMessage);
        }
    });

And you can see the data in the alert window.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top