我正在尝试使用 jQuery 跨域调用 Web 服务。
这是我调用服务的代码
$(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);
}
我正在从服务返回简单的字符串。
public string HelloWorld()
{
return "Hello World";
}
服务被调用,但我收到错误
未捕获的语法错误:意外的标记:
在 Chrome 的控制台窗口中。
我在从浏览器调用服务时收到此字符串:
{"HelloWorldResult":"Hello World"}
请让我知道我哪里出错了?
提前致谢。
您的 WCF 服务器应配置为启用jsonp
with CrossDomainScriptAccessEnabled
这是一个简单的工作示例
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";
}
}
这是 JavaScript 代码
<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>
现在您可以通过浏览器进行测试
http://localhost/test/hello
and
http://localhost/test/hello?callback=myfunc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)