Reputation: 804
I have the following working example, I'm trying to get http://detectlanguage.com via a jquery request. Since this will be a cross-domain request I'm using jsonp.
Here is a link in MSDN with a similar request where it's infered that jsonp
is the way to go.
Everything's fine, except the page throws an error Error: myCallback was not called
, the response I get from server is the following:
{"data":
{"detections":[
{"language":"ca",
"isReliable":false,
"confidence":0.14992503748125938
},
{"language":"en",
"isReliable":false,
"confidence":0.00 8103727714748784
}]
}
}
I've been searching all day in stackoverflow for answers regarding jsonp but haven't got it to work yet.
Any help is very much appreciated
UPDATED
Including AJAX call
$.ajax({
url: 'http://ws.detectlanguage.com/0.2/detect',
data: {
q: $('#hi').val(),
key:'demo'
},
jsonpCallback: 'myCallback',
dataType: "jsonp",
success: myCallback,
error: function(e,i,j){
$('#results').html(j)
}
});
I also have a javascript function called myCallback
:
function myCallback(response){
alert(response.data)
}
Upvotes: 2
Views: 24224
Reputation: 4866
I also spend a very long time looking around SO for a response. The solution for me had to do with the service, not ajax calls or jQuery. Specifically, the service needs to be set up to allow cross-domain access using this setting in web.config:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
...
<endpoint address="../YourService.svc"
binding="webHttpBinding"
bindingConfiguration="webHttpBindingWithJsonP"
contract="YourServices.IYourService"
behaviorConfiguration="webBehavior" />
Upvotes: 0
Reputation: 2008
The response doesnot seem to be jsonp, the jsonp response should be a javascript. Below is the code that works for me.
ajax request:
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "http://<your service url here>/HelloWorld?callback=?",
data: {projectID:1},
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
server side code returning jsonp (c#):
public void HelloWorld(int projectID,string callback)
{
String s = "Hello World !!";
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(s));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
Upvotes: 4