问题描述
我正在使用json在javascript文件中调用网络服务,但是仅当.asmx文件和javascript文件都在本地服务器上时,才会调用网络服务.服务器.
I am calling a webservice in javascript file using json but web service is called only when both of the .asmx file and javascript file are on my local server or both of the files are uploaded on live server.
但是我要测试从本地服务器上载到实时服务器上的Web服务.
but I want to test my webservice which is uploaded on my live server from my local server.
因此,请告诉我从本地服务器测试实时Web服务的方式.因为当我的Javascript文件也存在于实时上时,相同的Web服务可以正常工作,但是当javascript文件位于本地且Web服务处于实时服务器中时,无法正常工作
So please tell me the way by which I can test my live webservice from my local server.Because same web service is working fine when my Javascript file also present on live but not working when javascript file is on local and web service is on live server
请帮助
推荐答案
由于某些安全原因,您可以调用位于同一域上的Web服务.您将必须使用带填充的JSON(JSONP).
you can call the web service which is on same domain beacuse of some Security reasons.u will have to use JSON with padding (JSONP).
您的服务必须返回jsonp,这基本上是javascript代码.您需要从ajax请求中向服务提供回调函数,然后返回的是函数调用.
Your service has to return jsonp, which is basically javascript code. You need to supply a callback function to the service from your ajax request, and what is returned is the function call.
示例:1
Ajax请求:
function hello() {
$.ajax({
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://example.example.com/WebService.asmx/HelloWorld",
data: {}, // example of parameter being passed
dataType: "jsonp",
success: jsonpCallback,
});
}
function jsonpCallback(json) {
document.getElementById("result").textContent = JSON.stringify(json);
}
服务器端代码:
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();
}
示例:2
这篇关于通过javascript进行网络服务调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!